Download My weeks 1-7

Document related concepts

Java ConcurrentMap wikipedia , lookup

Transcript
CPSC150
Spring 2005
Dr. Lambert
Java
Lynn Lambert
CPSC150
Syllabus






Java
Java
CPSC150Lab
No attendance, but Class Assignments may/may not be
put on web; short turnaround
Come see me/Java expert early and often
Ask questions
Consult with (possibly non-expert) peers, but be
careful. >50% of your grade is exams.
Lynn Lambert
CPSC150
Why programming languages?
•Computers understand machine language
only
•Each computer has its own language
•All computer languages are in binary (1s and
0s)
•No computer understands English,
Powerpoint, or Java
Java
Lynn Lambert
CPSC150
A computer program: Add X to
Y and store in Z
In machine language:
 01040100 (already simplified to decimal)
 01050160
 04040506
 02060180
HUH!?
Java
Lynn Lambert
CPSC150
Assembly
Each machine instruction has matching, more
English-like assembler:
 Load X (was: 01040100)
 Load Y (was: 01050160)
 Add X Y Z (was: 04040506)
 Store Z (was: 02060180)
Better, but … all this for one addition!?
Java
Lynn Lambert
CPSC150
Java
z=x+y;
Much better!
BUT, no machines understand source code.
Only machine code.
Java
Lynn Lambert
CPSC150
Virtual Machine

Review:




Java developed to be platform independent


Java
Computers understand machine language only
Each computer has its own language
No computer understands English, Powerpoint, or Java
Virtual machine built on top of each actual machine to make
all machines (windows, mac, UNIX) look alike
Java compiles to byte-code – not machine code, but “virtual
machine code”
Lynn Lambert
CPSC150
Why Java?





Java
Java is a large, complete language
Works well with web applications
GUIs “part” of the language
Extensive libraries
(You will get C++ also)
Lynn Lambert
CPSC150
Java and BlueJ








Java
We will use BlueJ for program development
BlueJ runs on the Java virtual machine
BlueJ is IDE – lots of others (e.g., Eclipse)
BlueJ is free and available for Mac, Windows, UNIX
You will test and submit program using UNIX
Use your Hunter Creech Account
Download BlueJ for your home machines for development:
www.bluej.org
(download Java first: 1.4.2 is on PCS machines):
http://java.sun.com/j2se/1.4.2/download.html (Download
SDK, NOT JRE)
Lynn Lambert
CPSC150
Why BlueJ







Java
Easy to use
Object-oriented
Start programming immediately
GUI, not console-based
Object visualization using UML
Debugger, Editor, other standard stuff
Simple, not for advanced applications
Lynn Lambert
CPSC150
•Demo VNC
•BlueJ
•Shapes – compile
• Terms:
•Object, class, method, source code, parameter
• cp /usr/local/examples/shapes .
Java
Lynn Lambert
CPSC150
Week 2
Writing Java Code
Java
Lynn Lambert
CPSC150
Review

External View

In BlueJ main window,
Classes
 Object bench
 Class relationships
 Create Objects
 Call/Invoke Methods of objects

Java
Lynn Lambert
CPSC150
Source Code (Internal View)


import
Comments // single line
/* */ multiline
/**
*/ Javadoc
Class definitions
public class Picture
{
// fields
// constructors
// methods
}

Java
Lynn Lambert
CPSC150
Class details: fields/attributes


Lifetime/scope of class
private int myfield; // primitive



private String mystring; // class
private Circle sun;


user and library defined
BlueJ: primitive has data; object has pointer

Java
char, boolean, double, a few others
Clock example, ClockDisplay, NumberDisplay
Lynn Lambert
CPSC150
Class details: constructors



Initialize objects. Called when object is created
no return type
can be overloaded
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
}
Java
public Circle(int d, int x, int y, color c)
{
diameter = d;
xPosition = x;
yPosition = y;
color = c;
isVisible = false;
}
Lynn Lambert
CPSC150
Class Details: Methods

General Structure:
first line signature or header
public/private return-type name (param1name
param1type, param2name param2type) return type void

changeColor method from Circle:
formal parameter
public void changeColor(String newColor)
curly braces, stuff
{
inside is method body
color = newColor;
draw();
Java statements inside body,
e.g., single = assignment
}
method call (internal to class)
Java
Lynn Lambert
CPSC150
Method vs. Field







Java
Both have private or public
Both have types
Both have names
fields have ‘;’ at end of line/methods do not
methods have () (even without parameters); fields do
not
methods have a body; fields do not
fields have memory to hold information; methods do
not
Lynn Lambert
CPSC150
Field vs. Local variable




Java
local variables declare in a method; fields outside
of all methods
local variables have the lifetime of the method
call
local variables and fields have type and ‘;’
local variables do NOT have private/public
designation
Lynn Lambert
CPSC150
Writing methods:
More Java statements







Java
Arithmetic Expressions
Compound Assignment
System.out.println
this
new
dot notation
return
Lynn Lambert
CPSC150
Arithmetic




Java
+, /, *, -, %
Codepad (Choose view, then codepad)
Be careful about integer division
4/3 p r 3
Lynn Lambert
CPSC150
Compound Assignment

assignment:



compound assignment






answer = factor1 * factor2;
answer = answer + newsum;
answer += newsum;
answer -= diff;
answer *= product; // e.g., factorial
answer /= digit; // getting rid of digits
answer %= digit;
Use codepad
 int answer=30; answer %= 4; System.out.println("Answer is " + answer);
Java
Lynn Lambert
CPSC150
System.out.println()




To print out messages to a terminal
Can print strings or integers
Use + to concatenate/append. Be careful with
numbers
e.g.,
System.out.println("Answer is " + answer);
 System.out.println(answer + answer);
 System.out.println(“answer is” + answer + answer);

Java
Lynn Lambert
CPSC150
this
public void
changeColor(String newColor)
{
color = newColor;
draw();
}
public void
changeColor(String color)
{
this.color = color;
draw();
}
this specifies the
current object
Java
Lynn Lambert
CPSC150
new, dot notation
public void draw()
{
To create a new object,
use new. calls
constructor
wall = new Square();
wall.moveVertical(80);
wall.changeSize(100);
wall.makeVisible();
Extermal method call
dot notation
//rest of method from Picture class
}
Java
Lynn Lambert
CPSC150
return statement
public int sum(int x, int y)
{
type of method is
return type
int answer;
answer = x+y;
to return a value, use ‘return
return answer;
value’; can be calculation
}
Java
Lynn Lambert
CPSC150
Common Methods to Write


Wizard at writing code; let’s look at common
methods
Mutator method: change value of a field


Accessor method: get the value of a field

Java
e.g., setTime in Clock
e.g., getTime in Clock
Lynn Lambert
CPSC150
Common methods: Accessor
Retrieve the value of a field
 no parameter, return type is type of field
 method body is one line
public class fraction
{ // only a little bit defined
private int numerator;
private int denominator;

public int GetNum()
{
return numerator;
}
}
Java
Lynn Lambert
CPSC150
Common Method: mutator



Changes field value
void return type, one parameter is new value
not all fields have to have mutator methods
public class fraction
{// only a portion of this class
private int numerator;
private int denominator;
public void SetNum(int newvalue)
{
numerator = newvalue;
}
}
Java
Lynn Lambert
CPSC150
Conditionals
Execute code under some conditions
 In Canvas
public static Canvas getCanvas()
{ // only create Canvas if not already created
if (canvasSingleton == null) {

canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300,
Color.white);
}
canvasSingleton.setVisible(true);
return canvasSingleton;
}
Java
Lynn Lambert
CPSC150
if statements
if (booleanexpression)
java statement;
we don’t know about this
any Java statement you
know about
Java
Lynn Lambert
CPSC150
Boolean Expressions


Evaluate to be true or false
boolean variables



Java
boolean isVisible = false;
relational expressions (compares values)
logical expressions (compares expressions with
and, or, not)
Lynn Lambert
CPSC150
Relational Operators
for primitives
int x, y;
 x<y
 x <= y
 x>y
 x >= y
 x != y
 x == y // NOT x=y

Java
NOTE: most of these don’t work for classes (== is a
problem)
Lynn Lambert
CPSC150
Evaluating Boolean Expressions
int x=3; int y = 4; int z=5;
x<y
true
Java
x<y<z
error: < cannot be applied to boolean,int
x=y
error: incompatible types - found int; expected boolean
y == 4
true
z >= x
false
x != 3
false
(x + 4) < (y - 1)
7 < 3; false
Lynn Lambert
CPSC150
Logical Operators

and (&&, single & very different)



or (|| - on keyboard, called pipe symbol)



either value can be true
if it is cold or rainy, wear a coat (if either or both is true,
do)
not (!)


Java
both values must be true for the expression to be true
if it is cold and rainy, wear your winter raincoat (both
must be true)
changes the truth value of the expression
if it is not cold, do not wear a winter coat
Lynn Lambert
CPSC150
Logical Operators
int x=3; int y=10;
(x < y) && (y < 20)
(x == 3) || (y == 3)
Java
x < y; 3 < 10; true
y < 20; 10 < 20; true
true && true is true
x == 3 true.
short circuit evaluation
(y==3 false
true || false is true)
Lynn Lambert
CPSC150
More logical operators
int x=3; int y=10;
!(y=10)
(x != 3) || (y != 3)
Java
trick question
error
!(y==10)
y == 10 true
!true false
x != 3 false
Keep going. y != 3 true
false || true is true
Lynn Lambert
CPSC150
Yet more logical operators
int x=3; int y=10;
!((x+1 < 4) ||
(y <= 10))
!((x+1 < 4) &&
(y <= 10))
Java
x+1 = 4
4 < 4 false.keep going
y <= 10 true
false || true true
! true is false
4 < 4 false. DONE with
&&. Do not look at y
<=10.
!false true
Lynn Lambert
CPSC150
Strings and Classes




Java
== tests if objects are equal (point to the same
thing), NOT if they have the same content.
May return false when true should be returned
use equals
no corresponding <, lessthan,…
use compareTo
Lynn Lambert
CPSC150
CompareTo



Java
Returns 0 if 2 Strings are equal
Returns negative number if object<parameter
Returns positive number if object > parameter
Lynn Lambert
CPSC150
compareTo code
String s1 = “Here is a string”;
String s2 =“Here is another string”;
String s3 = “here is another string”;
if (s1.compareTo(s2) < 0)
// will print
System.out.println(“s1 less than s2”);
if (s2.compareTo(s1) < 0)
System.out.println(“s2 less than s1”); // will not print
if (s2.compareTo(s3) < 0) // case matters; uppercase < lowercase
System.out.println(“s2 less than s3”);
// will print
if (s3.compareTo(s2) < 0)
System.out.println(“s3 less than s2”); // will not print
Java
Lynn Lambert
CPSC150
More String comparisions
String s1 = “Here is a string”;
String s2 =“Here is a string”;
String s3 = “here is another string”;
if (s1.compareTo(s2) == 0)
System.out.println(“s1 is the same as s2”); // will print
if (s2.compareTo(s1) == 0)
System.out.println(“s2 still the same as s1”); // will print; symmetric
if (s2.equals(s1)) // compareTo == 0 is same as equals
System.out.println(“s2 is STILL the same as s1”); // will print
if (s3.compareTo(s2) == 0)
System.out.println(“s3 is the same as s2”);
// will not print
if (s1 == s2)
// will not print
System.out.println(“s1 and s2 point to the same object”);
Java
Lynn Lambert
CPSC150
if statements

if statement form:

if (boolean expression)
java statement;
if (x < y)
System.out.println(“x < y”);
Java
Lynn Lambert
you know both
parts now
CPSC150
if statements cautions







Java
MUST have ()s around boolean expression
no syntax error for non-boolean like expressions
only ONE statement in an if statement
no ';' after if condition
Make sure you account for values that are equal
use relational operators only with primitives
use equals, compareTo with String
Lynn Lambert
CPSC150
if-else

If you want to do one thing if a condition is true
and something else if not, use if-else.
form: if (condition)
Java statement
else
Java statement
if (x < y)
System.out.println(x + " is less than the other number”);
else
System.out.println(y + " is less than the other number”);

Java
Lynn Lambert
CPSC150
> one statement in an if
If you want to have more than one statement inside an
if or an else, use {}s:
if (x < y)
{
System.out.println(x + " is less than the other number”);
x = 0;
}
else
{
System.out.println(y + " is less than the other number”);
y = 0;
}
Java
Lynn Lambert
CPSC150
If-else cautions




Java
either if clause or else clause or both may have
{}s.
After statements inside if and else clause are
executed, control passes back to next sequential
statement
no ';' after else
Make sure you account for values that are equal
Lynn Lambert
CPSC150
Class Work
Write an if statement to assign x to y if x is greater than
y
 Consider a class
public class MyString
{ private String s;
// write method here
}
Write the method lessThan that takes a String as a
parameter and returns true if s (from MyString) is less
than its String parameter

Java
Lynn Lambert
CPSC150
Watch Out
if (3 < 4)
x = 3;
else
System.out.println(“3 < 4 is false”);
x = 0;
System.out.println("the value of x is " + x);
Java
Lynn Lambert
CPSC150
Embedded ifs


Java
If statements and if-else statements may be
embedded (if within if). simply evaluate them as
the Java code is executed:
if-else example is most common. sets up a table
of conditions
Lynn Lambert
CPSC150
Embedded if-else for table
if (ave >= 90)
grade = 'A';
else if ((ave < 90) && (ave >= 80))
// note: need ()s around entire condition
grade = 'B';
else if ((ave < 80) && (ave >=70))
grade = 'C';
else if ((ave < 70) && (ave >=60))
grade = 'D';
else if ((ave < 70) && (ave < 60))
grade = 'F';
Java
Lynn Lambert
CPSC150
Tracing through the embedded if
Java
Lynn Lambert
CPSC150
Fixing the embedded if
Java
if (ave >= 90)
grade = 'A';
else if (ave >= 80)
// We know (ave < 90) or we wouldn't be here
grade = 'B';
else if (ave >=70) // we know ave < 80
grade = 'C';
else if (ave >=60)
grade = 'D';
else
// if ((ave < 70) && (ave < 60))
grade = 'F';
Lynn Lambert
CPSC150
Cautions for embedded ifs



Java
Don't use redundant comparisons
Make sure you check for values that are equal
Account for out of range values
Lynn Lambert
CPSC150
Program style




Java
Put {}s on a line by themselves
indent {}s 2-3 spaces, statements one more than
that
All code outside if statements should line up
All code inside of if statements should line up.
Lynn Lambert
CPSC150
More complicated embedded ifs
if (x < 3)
if (y < 6)
System.out.println( "x and y between 3 and 6");
else
System.out.println( "x < 3; y >= 6");
else
if (y > 6)
System.out.println( "x and y not in 3-6 range");
else
System.out.println( "x >= 3); y <= 6 ");
Java
Lynn Lambert
CPSC150
Arrays and Loops
week 4
Chapter 4
Java
Lynn Lambert
CPSC150
Arrays
Each variable only holds one item
 if > 1 item wanted, need an array
 array that holds a word
 arrays hold elements all of the same type
char[ ] word = new char[4];
 holds 4 elements of type char

word
0
Java
1
2
3
Lynn Lambert
CPSC150
char[ ] word = new char[4];
two parts to an array:
index -- integer
element – type inside
array
word[3] = 'o';
word[0] = 'h';
'h'
0
1
2
3
'e'
'o'
0
1
2
3
'h'
'e'
'r'
'o'
0
1
2
3
word[2] = 'r';
word[1] = 'e';
Java
'h'
'h'
'e'
0
1
2
3
Lynn Lambert
CPSC150
Array manipulation
'h'
'e'
'r'
'o'
0
1
2
3
Can use variables for index OR elements
int i=3; char new = 'd';
word[i] = new;

'h'
'e'
'r'
'd'
0
1
2
3
can find length
word.length // is 4
 largest index is always length – 1
 word[4] is RUN time error

Java
Lynn Lambert
CPSC150
arrays and new
char[ ] word;
 creates word that is of type char array that
points to nothing
word = new word[4];
 creates array of 4 elements initialized to \u0000
(Java always initializes primitives to 0)
Java
Lynn Lambert
CPSC150
Myarray example
public class Myarray
{
private static Circle[]
circles;
private static double[] area;
// other stuff in the class
}
Java
Lynn Lambert
CPSC150
Myarray gets elements allocated
Create an object
circles = new Circle[4];
area = new double[4];

Java
Lynn Lambert
CPSC150
createcircles()
createcircles()
circles[0] = new Circle();

Java
Lynn Lambert
CPSC150
array creation summary
char[ ] word;
creates a space named word that contains null
 word = new char [4];
allocates 4 chars, initialized, word points to them
 classes: Circle[ ] mycircles;
same as word
 mycircles = new Circle[4];
allocates 4 spaces that contain null
 mycircles[0] = new Circle( );
creates an actual circle

Java
Lynn Lambert
CPSC150
Repetition in arrays
arrays often do the same thing
(e.g., for each Circle in array, create a Circle)

memorize this line
for (int i=0; i<circles.length; i++)
circles[i] = new Circle( );
Java
Lynn Lambert
CPSC150
Do: In a group



Java
Write code to declare a 4 character word array, then
write a loop to initialize chars in word to be 'A'
Write code to declare a 4 character array, then write a
loop to initalize chars in word to be ABCD (do this in a
loop). Hint: use a separate variable for the element
value (start with 'A')
Declare an int array with 10 integers and write a loop to
put the value of the index into the element (e.g.,
intarray[3] should have the value 3)
Lynn Lambert
CPSC150
CPSC 150 – Computers and Programming I
“while” and “for”
Structures
Dr. Roberto A. Flores
Java
Lynn Lambert
CPSC150
“while” structures
• It repeats a set of statements while a condition is true.
while ( condition )
{
is TRUE execute these statements;
}
Java
Lynn Lambert
CPSC150
“while” structures
• It repeats a set of statements while a condition is true.
while ( condition ) 1
{
is TRUE execute these statements;
}
2
3
The dynamics of “while”
1. Evaluate condition:
• if TRUE go to 2
• If FALSE go to 3
2. Execute statements, and then go to 1
3. Continue with next statement.
Java
Lynn Lambert
CPSC150
“while” structures
• It repeats a set of statements while a condition is true.
int speedLimit = 55;
int speed
= 0;
while ( speed < speedLimit )
{
speed = speed + 1;
}
// since we don’t want a ticket…
speed = speed - 1;
• What is the value of “speed” at this point?
Java
Lynn Lambert
CPSC150
“while” structures
• It repeats a set of statements while a condition is true.
int speedLimit = 55;
int speed
= 0;
1
initialize variables
in conditional
while ( speed < speedLimit )
2
{
modify variables
speed = speed + 1;
in conditional
}
// since we don’t want a ticket…
speed = speed - 1;
Java
Lynn Lambert
CPSC150
“while” structures
• Adding the values of an array of integers
int grades[] = new int[1000];
/*
the values of the elements
are somehow initialized here.
*/
int i
= 0;
int sum = 0;
while ( i < grades.length ) {
sum += grades[i];
i++;
}
System.out.println(“The sum is ” + sum);
Java
Lynn Lambert
CPSC150
“while” structures:
Exercises
• Determine the output of the following methods:
public void foo1() {
int i=0;
while (i <= 20) {
System.out.println( i );
i = i + 4;
}
}
public void foo2() {
int i = 20;
while (i > 0) {
i = i / 2;
System.out.println( i );
}
}
Java
Lynn Lambert
CPSC150
“while” structures:
Exercises
1. Write a method named “countDown” that receives an integer
parameter named “number”, and displays (using
System.out.println) all numbers from the number down to 0.
• For example, if the parameter was 8, the method should
display numbers 7, 6, 5, 4, 3, 2, 1, 0, in this order and with
each number in one line.
2. Write a method named “countEven” that receives an integer
parameter named “number”, displays (using
System.out.println) all even numbers between 0 and the
number received, and returns a integer value with the number of
even numbers displayed.
• For example, if the parameter was 8, the method should
display numbers 2, 4 and 6, in this order and with each
number in one line, and return a value of 3 (which is how
many even numbers were between 0 and 8).
Java
Lynn Lambert
CPSC150
“while” structures:
Exercises
3. Write a method named “reverse” that receives an integer
parameter named “number” and displays (using
System.out.println) the number with all digits reversed.
The method should only work with positive parameter
values.
• For example, if the number was 2001, the method
should display 1002. (Hint: use modulus by 10 to
extract the last digit from the number, and then divide
the number by 10 before extracting the next digit).
Java
Lynn Lambert
CPSC150
“for” structures
• It (also) repeats statements while a condition is true.
1
2
4
loop
initial
modify
for ( statement ; condition; statement )
{
statements;
3
}
5
The dynamics of “for”
1. Initialize condition variables.
2. Evaluate loop condition:
• if TRUE go to 3
• If FALSE go to 5
3. Execute statements; then go to 4
4. Modify condition variables; then go to 2
5. Continue with next statements.
Java
Lynn Lambert
CPSC150
Revisiting “while” exercise
with “for”
• Write a method named “countEven” that receives an
integer parameter named “number”, displays (using
System.out.println) all even numbers between 0 and
the number received, and returns a integer value with the
number of even numbers displayed.
public int countEven(int number) {
int count = 0, i = 2;
while (i < number) {
if (i % 2 == 0) {
System.out.println( i );
count++;
}
i++;
}
return count;
}
Java
Lynn Lambert
CPSC150
“for” structures: Exercises
1. Write a method named “factorial” that calculates the
factorial of an integer parameter named “number” (where
factorial is the multiplication of all numbers from 1 to
number-1). The method should return an integer number
with the result of the factorial, and it should work only with
positive numbers (return 0 in the case of non-positive
parameter numbers).
2. Write a method named “prime” that returns a boolean
value indicating whether an integer parameter named
“number” is a prime number (where a prime number is a
number that is not divisible without remainder by any other
numbers except 1 and the number itself). The method
should work only with positive numbers (return false if a
negative parameter number is given).
Sample list of prime numbers:
2, 3, 5, 7, 11, 13, 19, 23…CPSC150
Lynn Lambert
Java
“for” structures: Exercises
3. Write a method named “digits” that displays (using
System.out.println) the digits of an integer parameter
named “number” separated by dashes (“-”). For example,
when receiving the number 1234 as a parameter, the
method should display “1-2-3-4”.
• Hints: use an array to store each digit as you extract them
using the modulus operator. Since these digits are stored in
the array in the inverse order as they are found in the
number, you will need to print them backwards. Also, note
that the last digit does not have a trailing dash!
Java
Lynn Lambert
CPSC150
Containers
(ArrayList)
Chapter 4
Java
Lynn Lambert
CPSC150
ArrayList


Like arrays, but have built in operators
Use library (package)
import java.util.ArrayList;

Declare variable
private ArrayList circles;


Java
To create a list
circles = new ArrayList( ); // not NOT Circle
To add an element to the list (like Circle c)
circles.add(c)
Lynn Lambert
CPSC150
More ArrayList methods
 To
find the size:
circles.size();
 To
retrieve an element:
circles.get(1); // returns the second element
 To
remove an element
circles.remove(1); // removes the second element
Java
Lynn Lambert
CPSC150
ArrayList loop
Remember the ()s
unlike arrays
for loop with index
for (int i=0;i<circles.size( ); i++)
circles.get(i); // this returns the ith circle
 iterators
increment
part of
import java.util.Iterator;
body
for (Iterator it = circles.iterator();
it.hasNext( ); it.next( ))
;

Java
Lynn Lambert
CPSC150
Chapter 6
Testing
Java
Lynn Lambert
CPSC150
Testing/Debugging
Syntax errors: Initially fixing syntax errors the hard
part. After that, fixing logic errors:
 Testing: Ensuring that your code works
 Debugging: finding where code is incorrect
Java
Lynn Lambert
CPSC150
Levels of Testing





Java
Unit testing
Application testing
Always start at the lowest level
Test after every method is written
Use these tests throughout. after each method,
run all of the old tests
Lynn Lambert
CPSC150
The good, the bad, the ugly



Java
Test cases that will work
Test cases that will not work
Test cases that should not happen
Lynn Lambert
CPSC150
Types of Testing (in BlueJ)



Inspection
System.out.println
Regression Testing


To do that, Test Harness/Test Rig



Java
Create tests and rerun them for each new development
Class whose sole purpose is to test another class
To do that, Automatic Testing using junit
To do that, Record Tests
Lynn Lambert
CPSC150
Example


Java
day
mastermind
Lynn Lambert
CPSC150