CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert.
-
date post
20-Dec-2015 -
Category
Documents
-
view
227 -
download
0
Transcript of CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert.
Java Lynn Lambert CPSC150
CPSC150CPSC150
Spring 2005Spring 2005
Dr. LambertDr. Lambert
Java Lynn Lambert CPSC150
SyllabusSyllabus
JavaJava CPSC150LabCPSC150Lab No attendance, but Class Assignments No attendance, but Class Assignments
may/may not be put on web; short may/may not be put on web; short turnaroundturnaround
Come see me/Java expert early and oftenCome see me/Java expert early and often Ask questionsAsk questions Consult with (possibly non-expert) peers, Consult with (possibly non-expert) peers,
but be careful. >50% of your grade is but be careful. >50% of your grade is exams.exams.
Java Lynn Lambert CPSC150
Why programming Why programming languages?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: A computer program: Add X to Y and store in Add X to Y and store in
ZZ
In machine language:In machine language: 01040100 01040100 (already simplified to decimal)(already simplified to decimal)
01050160 01050160 0404050604040506 0206018002060180
HUH!?HUH!?
Java Lynn Lambert CPSC150
AssemblyAssembly
Each machine instruction has matching, Each machine instruction has matching, more English-like assembler:more English-like assembler:
Load X (was: 01040100)Load X (was: 01040100) Load Y (was: 01050160) Load Y (was: 01050160) Add X Y Z (was: 04040506)Add X Y Z (was: 04040506) Store Z (was: 02060180)Store Z (was: 02060180)
Better, but … all this for one addition!?Better, but … all this for one addition!?
Java Lynn Lambert CPSC150
JavaJava
z=x+y;z=x+y;
Much better!Much better!
BUT, no machines understand BUT, no machines understand source codesource code. Only . Only machine code.machine code.
Java Lynn Lambert CPSC150
Virtual MachineVirtual Machine Review:Review:
Computers understand machine language onlyComputers understand machine language only Each computer has its own languageEach computer has its own language No computer understands English, Powerpoint, No computer understands English, Powerpoint,
or Javaor Java
Java developed to be platform independentJava developed to be platform independent Virtual machine built on top of each actual Virtual machine built on top of each actual
machine to make all machines (windows, mac, machine to make all machines (windows, mac, UNIX) look alikeUNIX) look alike
Java compiles to byte-code – not machine code, Java compiles to byte-code – not machine code, but “virtual machine code”but “virtual machine code”
Java Lynn Lambert CPSC150
Why Java?Why Java?
Java is a large, complete languageJava is a large, complete language Works well with web applicationsWorks well with web applications GUIs “part” of the languageGUIs “part” of the language Extensive librariesExtensive libraries (You will get C++ also)(You will get C++ also)
Java Lynn Lambert CPSC150
Java and BlueJJava and BlueJ We will use BlueJ for program developmentWe will use BlueJ for program development BlueJ runs on the Java virtual machineBlueJ runs on the Java virtual machine BlueJ is IDE – lots of others (e.g., Eclipse)BlueJ is IDE – lots of others (e.g., Eclipse) BlueJ is free and available for Mac, Windows, BlueJ is free and available for Mac, Windows,
UNIXUNIX You will test and submit program using UNIXYou will test and submit program using UNIX Use your Hunter Creech AccountUse your Hunter Creech Account Download BlueJ for your home machines for Download BlueJ for your home machines for
development: development: www.bluej.orgwww.bluej.org (download Java first: 1.4.2 is on PCS machines): (download Java first: 1.4.2 is on PCS machines):
http://java.sun.com/j2se/1.4.2/download.htmlhttp://java.sun.com/j2se/1.4.2/download.html (Download (Download SDKSDK, NOT , NOT JREJRE))
Java Lynn Lambert CPSC150
Why BlueJWhy BlueJ
Easy to useEasy to use Object-orientedObject-oriented Start programming immediatelyStart programming immediately GUI, not console-basedGUI, not console-based Object visualization using UMLObject visualization using UML Debugger, Editor, other standard stuffDebugger, Editor, other standard stuff Simple, not for advanced applicationsSimple, not for advanced applications
Java 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 2Week 2
Writing Java CodeWriting Java Code
Java Lynn Lambert CPSC150
ReviewReview
External ViewExternal View In BlueJ main window, In BlueJ main window,
ClassesClasses Object benchObject bench Class relationships Class relationships Create ObjectsCreate Objects Call/Invoke Methods of objectsCall/Invoke Methods of objects
Java Lynn Lambert CPSC150
Source Code (Internal Source Code (Internal View)View)
importimport Comments Comments // single line// single line
/* */ multiline/* */ multiline/** */ Javadoc/** */ Javadoc
Class definitionsClass definitionspublic class Picturepublic class Picture{{// fields// fields// constructors// constructors// methods// methods}}
Java Lynn Lambert CPSC150
Class details: Class details: fields/attributesfields/attributes
Lifetime/scope of classLifetime/scope of class private int myfield; // primitiveprivate int myfield; // primitive
char, boolean, double, a few otherschar, boolean, double, a few others private String mystring; // classprivate String mystring; // class private Circle sun;private Circle sun;
user and library defineduser and library defined BlueJ: primitive has data; object has BlueJ: primitive has data; object has
pointerpointer Clock example, ClockDisplay, NumberDisplayClock example, ClockDisplay, NumberDisplay
Java Lynn Lambert CPSC150
Class details: Class details: constructorsconstructors
Initialize objects. Called when object is createdInitialize objects. Called when object is created no return typeno return type can be overloadedcan be overloaded
public Circle()public Circle() {{
diameter = 30;diameter = 30;xPosition = 20;xPosition = 20;yPosition = 60;yPosition = 60;color = "blue";color = "blue";isVisible = false;isVisible = false;
}}
public Circle(int d, int x, int y, color public Circle(int d, int x, int y, color c)c) {{
diameter = d;diameter = d;xPosition = x;xPosition = x;yPosition = y;yPosition = y;color = c;color = c;isVisible = false;isVisible = false;
}}
Java Lynn Lambert CPSC150
Class Details: MethodsClass Details: Methods
General Structure:General Structure:public/private return-type name public/private return-type name
(param1name param1type, param2name (param1name param1type, param2name param2type)param2type)
changeColor method from Circle:changeColor method from Circle: public void changeColor(String newColor)public void changeColor(String newColor) {{
color = newColor;color = newColor;draw();draw();
}}
return type void
first line signature or header
method call (internal to class)
Java statements inside body, e.g., single = assignment
curly braces, stuff inside is method body
formal parameter
Java Lynn Lambert CPSC150
Method vs. FieldMethod vs. Field
Both have private or publicBoth have private or public Both have typesBoth have types Both have namesBoth have names fields have ‘;’ at end of line/methods do notfields have ‘;’ at end of line/methods do not methods have () (even without methods have () (even without
parameters); fields do notparameters); fields do not methods have a body; fields do notmethods have a body; fields do not fields have memory to hold information; fields have memory to hold information;
methods do notmethods do not
Java Lynn Lambert CPSC150
Field vs. Local variableField vs. Local variable
local variables declare in a method; local variables declare in a method; fields outside of all methodsfields outside of all methods
local variables have the lifetime of local variables have the lifetime of the method callthe method call
local variables and fields have type local variables and fields have type and ‘;’and ‘;’
local variables do NOT have local variables do NOT have private/public designationprivate/public designation
Java Lynn Lambert CPSC150
Writing methods:Writing methods:More Java statementsMore Java statements
Arithmetic ExpressionsArithmetic Expressions Compound AssignmentCompound Assignment System.out.printlnSystem.out.println thisthis newnew dot notationdot notation returnreturn
Java Lynn Lambert CPSC150
ArithmeticArithmetic
+, /, *, -, %+, /, *, -, % Codepad (Choose view, then Codepad (Choose view, then
codepad)codepad) Be careful about integer divisionBe careful about integer division 4/3 4/3 rr 3 3
Java Lynn Lambert CPSC150
Compound AssignmentCompound Assignment assignment:assignment:
answer = factor1 * factor2;answer = factor1 * factor2; answer = answer + newsum;answer = answer + newsum;
compound assignmentcompound assignment answer += newsum;answer += newsum; answer -= diff;answer -= diff; answer *= product; // e.g., factorialanswer *= product; // e.g., factorial answer /= digit; // getting rid of digitsanswer /= digit; // getting rid of digits answer %= digit; answer %= digit;
Use codepadUse codepad int answer=30; answer %= 4; int answer=30; answer %= 4;
System.out.println("Answer is " + answer);System.out.println("Answer is " + answer);
Java Lynn Lambert CPSC150
System.out.println()System.out.println()
To print out messages to a terminalTo print out messages to a terminal Can print strings or integersCan print strings or integers Use + to concatenate/append. Be Use + to concatenate/append. Be
careful with numberscareful with numbers e.g.,e.g.,
System.out.println("Answer is " + answer); System.out.println("Answer is " + answer); System.out.println(answer + answer);System.out.println(answer + answer); System.out.println(“answer is” + answer + System.out.println(“answer is” + answer +
answer);answer);
Java Lynn Lambert CPSC150
thisthis
public void public void
changeColor(String newColor)changeColor(String newColor)
{{
color = newColor;color = newColor;
draw();draw();
}}
public void public void changeColor(String color)changeColor(String color) {{
this.color = color;this.color = color;draw();draw();
}}
this specifies the current object
Java Lynn Lambert CPSC150
new, dot notationnew, dot notation
public void draw()public void draw()
{{
wall = new Square();wall = new Square();
wall.moveVertical(80);wall.moveVertical(80);
wall.changeSize(100);wall.changeSize(100);
wall.makeVisible();wall.makeVisible();//rest of method from Picture class//rest of method from Picture class
}}
To create a new object, use new. calls
constructor
Extermal method calldot notation
Java Lynn Lambert CPSC150
return statementreturn statement
public int sum(int x, int y)public int sum(int x, int y)
{{
int answer;int answer;
answer = x+y;answer = x+y;
return answer;return answer;
}}
type of method is return type
to return a value, use ‘return value’; can be
calculation
Java Lynn Lambert CPSC150
Common Methods to Common Methods to WriteWrite
Wizard at writing code; let’s look at Wizard at writing code; let’s look at common methodscommon methods
Mutator method: change value of a Mutator method: change value of a fieldfield e.g., setTime in Clocke.g., setTime in Clock
Accessor method: get the value of a Accessor method: get the value of a fieldfield e.g., getTime in Clocke.g., getTime in Clock
Java Lynn Lambert CPSC150
Common methods: Common methods: AccessorAccessor
Retrieve the value of a fieldRetrieve the value of a field no parameter, return type is type of fieldno parameter, return type is type of field method body is one linemethod body is one linepublic class fractionpublic class fraction{ // only a little bit defined{ // only a little bit defined private int numerator;private int numerator; private int denominator;private int denominator;
public int GetNum()public int GetNum(){{return numerator;return numerator;}}}}
Java Lynn Lambert CPSC150
Common Method: Common Method: mutatormutator
Changes field valueChanges field value void return type, one parameter is new valuevoid return type, one parameter is new value not all fields have to have mutator methodsnot all fields have to have mutator methodspublic class fractionpublic class fraction{// only a portion of this class{// only a portion of this class private int numerator;private int numerator; private int denominator;private int denominator;
public void SetNum(int newvalue)public void SetNum(int newvalue){{numerator = newvalue;numerator = newvalue;}}}}
Java Lynn Lambert CPSC150
ConditionalsConditionals Execute code under some conditionsExecute code under some conditions In CanvasIn Canvaspublic static Canvas getCanvas()public static Canvas getCanvas()
{ // only create Canvas if not already created{ // only create Canvas if not already created if (canvasSingleton == null) {if (canvasSingleton == null) {
canvasSingleton = new Canvas("BlueJ Shapes Demo", canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, 300, 300,
Color.white);Color.white);
}} canvasSingleton.setVisible(true);canvasSingleton.setVisible(true); return canvasSingleton;return canvasSingleton;}}
Java Lynn Lambert CPSC150
if statementsif statements
if (booleanexpression)if (booleanexpression)
java statement;java statement;
any Java statement you know about
we don’t know about this
Java Lynn Lambert CPSC150
Boolean ExpressionsBoolean Expressions
Evaluate to be true or falseEvaluate to be true or false boolean variablesboolean variables
boolean isVisible = false;boolean isVisible = false; relational expressions (compares relational expressions (compares
values)values) logical expressions (compares logical expressions (compares
expressions with and, or, not)expressions with and, or, not)
Java Lynn Lambert CPSC150
Relational OperatorsRelational Operatorsfor primitivesfor primitives
int x, y;int x, y; x < yx < y x <= yx <= y x > yx > y x >= yx >= y x != yx != y x == y // NOT x=yx == y // NOT x=y
NOTE: most of these don’t work for NOTE: most of these don’t work for classes (== is a problem)classes (== is a problem)
Java Lynn Lambert CPSC150
Evaluating Boolean Evaluating Boolean ExpressionsExpressions
int x=3; int y = 4; int z=5;int x=3; int y = 4; int z=5;
x < yx < y
x < y < zx < y < z
x = yx = y
y == 4y == 4
z >= xz >= x
x != 3x != 3
(x + 4) < (y - 1)(x + 4) < (y - 1)
truetrue
error: error: < cannot be applied to boolean,int< cannot be applied to boolean,int
error: incompatible types - found int; expected boolean error: incompatible types - found int; expected boolean
truetrue
falsefalse
falsefalse
7 < 3; false7 < 3; false
Java Lynn Lambert CPSC150
Logical OperatorsLogical Operators and (&&, single & very different)and (&&, single & very different)
both values must be true for the expression to be both values must be true for the expression to be truetrue
if it is cold and rainy, wear your winter raincoat if it is cold and rainy, wear your winter raincoat (both must be true)(both must be true)
or (|| - on keyboard, called pipe symbol)or (|| - on keyboard, called pipe symbol) either value can be trueeither value can be true if it is cold or rainy, wear a coat (if either or both is if it is cold or rainy, wear a coat (if either or both is
true, do)true, do) not (!)not (!)
changes the truth value of the expressionchanges the truth value of the expression if it is not cold, do not wear a winter coatif it is not cold, do not wear a winter coat
Java Lynn Lambert CPSC150
Logical OperatorsLogical Operators
int x=3; int y=10;int x=3; int y=10;
(x < y) && (y < 20)(x < y) && (y < 20)
(x == 3) || (y == 3)(x == 3) || (y == 3)
x < y; 3 < 10; truex < y; 3 < 10; true
y < 20; 10 < 20; truey < 20; 10 < 20; true
true && true is truetrue && true is true
x == 3 true.x == 3 true.
short circuit short circuit evaluationevaluation
(y==3 false(y==3 false
true || false is true)true || false is true)
Java Lynn Lambert CPSC150
More logical operatorsMore logical operators
int x=3; int y=10;int x=3; int y=10;
!(y=10)!(y=10)
(x != 3) || (y != 3)(x != 3) || (y != 3)
trick questiontrick question
errorerror
!(y==10)!(y==10)
y == 10 truey == 10 true
!true false!true false
x != 3 falsex != 3 false
Keep going. y != 3 Keep going. y != 3 truetrue
false || true is truefalse || true is true
Java Lynn Lambert CPSC150
Yet more logical Yet more logical operatorsoperators
int x=3; int y=10;int x=3; int y=10;!((x+1 < 4) ||!((x+1 < 4) ||
(y <= 10))(y <= 10))
!((x+1 < 4) &&!((x+1 < 4) &&
(y <= 10))(y <= 10))
x+1 = 4x+1 = 44 < 4 false.keep 4 < 4 false.keep
goinggoingy <= 10 truey <= 10 truefalse || true truefalse || true true! true is false! true is false4 < 4 false. DONE 4 < 4 false. DONE
with &&. Do not with &&. Do not look at y <=10.look at y <=10.
!false true!false true
Java Lynn Lambert CPSC150
Strings and ClassesStrings and Classes
== tests if objects are equal (point == tests if objects are equal (point to the same thing), NOT if they have to the same thing), NOT if they have the same content. May return false the same content. May return false when true should be returnedwhen true should be returned
use equalsuse equals no corresponding <, lessthan,…no corresponding <, lessthan,… use compareTouse compareTo
Java Lynn Lambert CPSC150
CompareToCompareTo
Returns 0 if 2 Strings are equalReturns 0 if 2 Strings are equal Returns negative number if Returns negative number if
object<parameterobject<parameter Returns positive number if object > Returns positive number if object >
parameterparameter
Java Lynn Lambert CPSC150
compareTo codecompareTo code
String s1 = “Here is a string”;String s1 = “Here is a string”;String s2 =“Here is another string”;String s2 =“Here is another string”;String s3 = “here is another string”;String s3 = “here is another string”;if (s1.compareTo(s2) < 0)if (s1.compareTo(s2) < 0) System.out.println(“s1 less than s2”); System.out.println(“s1 less than s2”); if (s2.compareTo(s1) < 0)if (s2.compareTo(s1) < 0) System.out.println(“s2 less than s1”); System.out.println(“s2 less than s1”); if (s2.compareTo(s3) < 0) // case matters; uppercase if (s2.compareTo(s3) < 0) // case matters; uppercase
< lowercase< lowercase System.out.println(“s2 less than s3”); System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0)if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”); System.out.println(“s3 less than s2”);
// will print// will print
// will not print// will not print
// will print// will print
// will not print// will not print
Java Lynn Lambert CPSC150
More String More String comparisionscomparisions
String s1 = “Here is a string”;String s1 = “Here is a string”;String s2 =“Here is a string”;String s2 =“Here is a string”;String s3 = “here is another string”;String s3 = “here is another string”;if (s1.compareTo(s2) == 0)if (s1.compareTo(s2) == 0) System.out.println(“s1 is the same as s2”);System.out.println(“s1 is the same as s2”);if (s2.compareTo(s1) == 0)if (s2.compareTo(s1) == 0) System.out.println(“s2 still the same as s1”);System.out.println(“s2 still the same as s1”);if (s2.equals(s1))if (s2.equals(s1)) System.out.println(“s2 is STILL the same as s1”);System.out.println(“s2 is STILL the same as s1”);if (s3.compareTo(s2) == 0) if (s3.compareTo(s2) == 0) System.out.println(“s3 is the same as s2”);System.out.println(“s3 is the same as s2”);if (s1 == s2)if (s1 == s2) System.out.println(“s1 and s2 point to the same System.out.println(“s1 and s2 point to the same
object”);object”);// will not print// will not print
// will print; symmetric// will print; symmetric
// will print// will print
// will print// will print
// will not print// will not print
// compareTo == 0 is same as equals// compareTo == 0 is same as equals
Java Lynn Lambert CPSC150
if statementsif statements if statement form:if statement form:
if (boolean expression) if (boolean expression)
java statement;java statement;
if (x < y)if (x < y)
System.out.println(“x < y”);System.out.println(“x < y”);
you know both parts
now
Java Lynn Lambert CPSC150
if statements cautionsif statements cautions MUST have ()s around boolean expressionMUST have ()s around boolean expression no syntax error for non-boolean like no syntax error for non-boolean like
expressionsexpressions only ONE statement in an if statementonly ONE statement in an if statement no ';' after if conditionno ';' after if condition Make sure you account for values that are Make sure you account for values that are
equalequal use relational operators only with use relational operators only with
primitivesprimitives use equals, compareTo with Stringuse equals, compareTo with String
Java Lynn Lambert CPSC150
if-elseif-else
If you want to do one thing if a condition is If you want to do one thing if a condition is true and something else if not, use if-else.true and something else if not, use if-else. form: if (condition)form: if (condition)
Java statementJava statement elseelse Java statementJava statement
if (x < y)if (x < y) System.out.println(x + " is less than the other System.out.println(x + " is less than the other
number”);number”);elseelse System.out.println(y + " is less than the other System.out.println(y + " is less than the other
number”);number”);
Java Lynn Lambert CPSC150
> one statement in an if> one statement in an ifIf you want to have more than one statement If you want to have more than one statement
inside an if or an else, use {}s:inside an if or an else, use {}s:if (x < y) if (x < y)
{{
System.out.println(x + " is less than the System.out.println(x + " is less than the other number”);other number”);
x = 0;x = 0;
}}
elseelse
{{
System.out.println(y + " is less than the other System.out.println(y + " is less than the other number”);number”);
y = 0;y = 0;
}}
Java Lynn Lambert CPSC150
If-else cautionsIf-else cautions
either if clause or else clause or both either if clause or else clause or both may have {}s.may have {}s.
After statements inside if and else After statements inside if and else clause are executed, control passes clause are executed, control passes back to next sequential statementback to next sequential statement
no ';' after elseno ';' after else Make sure you account for values Make sure you account for values
that are equalthat are equal
Java Lynn Lambert CPSC150
Class WorkClass Work Write an if statement to assign x to y if x is Write an if statement to assign x to y if x is
greater than ygreater than y Consider a classConsider a classpublic class MyStringpublic class MyString{ private String s;{ private String s;// write method here// write method here}}Write the method lessThan that takes a String Write the method lessThan that takes a String
as a parameter and returns true if s (from as a parameter and returns true if s (from MyString) is less than its String parameterMyString) is less than its String parameter
Java Lynn Lambert CPSC150
Watch OutWatch Out
if (3 < 4)if (3 < 4)
x = 3;x = 3;
elseelse
System.out.println(“3 < 4 is false”);System.out.println(“3 < 4 is false”);
x = 0;x = 0;
System.out.println(System.out.println("the value of x is " + "the value of x is " + x);x);
Java Lynn Lambert CPSC150
Embedded ifsEmbedded ifs
If statements and if-else statements If statements and if-else statements may be embedded (if within if). may be embedded (if within if). simply evaluate them as the Java simply evaluate them as the Java code is executed:code is executed:
if-else example is most common. if-else example is most common. sets up a table of conditionssets up a table of conditions
Java Lynn Lambert CPSC150
Embedded if-else for Embedded if-else for tabletable
if (ave >= 90)if (ave >= 90) grade = 'A';grade = 'A';else if ((ave < 90) && (ave >= 80))else if ((ave < 90) && (ave >= 80)) // note: need ()s around entire condition// note: need ()s around entire condition grade = 'B'; grade = 'B'; else if ((ave < 80) && (ave >=70))else if ((ave < 80) && (ave >=70)) grade = 'C';grade = 'C';else if ((ave < 70) && (ave >=60))else if ((ave < 70) && (ave >=60)) grade = 'D';grade = 'D';else if ((ave < 70) && (ave < 60))else if ((ave < 70) && (ave < 60)) grade = 'F';grade = 'F';
Java Lynn Lambert CPSC150
Tracing through the Tracing through the embedded ifembedded if
Java Lynn Lambert CPSC150
Fixing the embedded ifFixing the embedded ifif (ave >= 90)if (ave >= 90) grade = 'A';grade = 'A';else if (ave >= 80)else if (ave >= 80)// We know (ave < 90) or we wouldn't be // We know (ave < 90) or we wouldn't be
herehere grade = 'B'; grade = 'B'; else if (ave >=70) // we know ave < 80else if (ave >=70) // we know ave < 80 grade = 'C';grade = 'C';else if (ave >=60)else if (ave >=60) grade = 'D';grade = 'D';else else // if ((ave < 70) && (ave < 60))// if ((ave < 70) && (ave < 60)) grade = 'F';grade = 'F';
Java Lynn Lambert CPSC150
Cautions for embedded Cautions for embedded ifsifs
Don't use redundant comparisonsDon't use redundant comparisons Make sure you check for values that Make sure you check for values that
are equalare equal Account for out of range valuesAccount for out of range values
Java Lynn Lambert CPSC150
Program styleProgram style
Put {}s on a line by themselvesPut {}s on a line by themselves indent {}s 2-3 spaces, statements indent {}s 2-3 spaces, statements
one more than thatone more than that All code outside if statements should All code outside if statements should
line upline up All code inside of if statements All code inside of if statements
should line up.should line up.
Java Lynn Lambert CPSC150
More complicated More complicated embedded ifsembedded ifs
if (x < 3)if (x < 3) if (y < 6)if (y < 6) System.out.println( "x and y between 3 System.out.println( "x and y between 3
and 6");and 6"); elseelse System.out.println( "x < 3; y >= 6");System.out.println( "x < 3; y >= 6");elseelse if (y > 6)if (y > 6) System.out.println( "x and y not in 3-6 System.out.println( "x and y not in 3-6
range"); range"); elseelse System.out.println( "x >= 3); y <= 6 ");System.out.println( "x >= 3); y <= 6 ");
Java Lynn Lambert CPSC150
Arrays and LoopsArrays and Loopsweek 4week 4
Chapter 4Chapter 4
Java Lynn Lambert CPSC150
Each variable only holds one itemEach variable only holds one item if > 1 item wanted, need an arrayif > 1 item wanted, need an array array that holds a wordarray that holds a word arrays hold elements all of the same arrays hold elements all of the same
typetype
char[ ] word = new char[4];char[ ] word = new char[4]; holds 4 elements of type charholds 4 elements of type char
ArraysArrays
0 1 32
word
Java Lynn Lambert CPSC150
char[ ] word = new char[4];
two parts to an array:
index -- integer
element – type inside array
'h' 'e'
0 1 32
'h'
0 1 32
word[1] = 'e';
'h' 'e' 'o''r'
0 1 32
'h' 'e' 'o'
0 1 32
word[3] = 'o';
word[2] = 'r';
word[0] = 'h';
Java Lynn Lambert CPSC150
Can use variables for index OR elementsCan use variables for index OR elementsint i=3; char new = 'd';int i=3; char new = 'd';word[i] = new;word[i] = new;
can find lengthcan find lengthword.length // is 4word.length // is 4 largest index is always length – 1largest index is always length – 1 word[4] is RUN time errorword[4] is RUN time error
Array manipulationArray manipulation
'h' 'e' 'o''r'
0 1 32
'h' 'e' 'd''r'
0 1 32
Java Lynn Lambert CPSC150
arrays and newarrays and new
char[ ] word;char[ ] word; creates word that is of type char creates word that is of type char
array that points to nothingarray that points to nothing
word = new word[4];word = new word[4]; creates array of 4 elements creates array of 4 elements
initialized to \u0000 (Java always initialized to \u0000 (Java always initializes primitives to 0)initializes primitives to 0)
Java Lynn Lambert CPSC150
Myarray exampleMyarray example
public class Myarraypublic class Myarray
{{
private static private static Circle[] circles;Circle[] circles;
private static private static double[] area; double[] area;
// other stuff in the // other stuff in the classclass
} }
Java Lynn Lambert CPSC150
Myarray gets elements Myarray gets elements allocatedallocated
Create an object Create an object
circles = new circles = new Circle[4];Circle[4];
area = new area = new double[4];double[4];
Java Lynn Lambert CPSC150
createcircles()createcircles()
createcircles()createcircles()
circles[0] = new circles[0] = new Circle(); Circle();
Java Lynn Lambert CPSC150
array creation summaryarray creation summary char[ ] word;char[ ] word;creates a space named word that contains nullcreates a space named word that contains null word = new char [4];word = new char [4];allocates 4 chars, initialized, word points to allocates 4 chars, initialized, word points to
themthem classes: Circle[ ] mycircles;classes: Circle[ ] mycircles;same as word same as word mycircles = new Circle[4];mycircles = new Circle[4];allocates 4 spaces that contain nullallocates 4 spaces that contain null mycircles[0] = new Circle( );mycircles[0] = new Circle( );creates an actual circlecreates an actual circle
Java Lynn Lambert CPSC150
Repetition in arraysRepetition in arrays
arrays often do the same thingarrays often do the same thing
(e.g., for each Circle in array, create a (e.g., for each Circle in array, create a Circle)Circle)
for (int i=0; i<circles.length; i++)for (int i=0; i<circles.length; i++)
circles[i] = new Circle( );circles[i] = new Circle( );
memorize this line
Java Lynn Lambert CPSC150
Do: In a groupDo: In a group
Write code to declare a 4 character word Write code to declare a 4 character word array, then write a loop to initialize chars in array, then write a loop to initialize chars in word to be 'A' word to be 'A'
Write code to declare a 4 character array, then Write code to declare a 4 character array, then write a loop to initalize chars in word to be write a loop to initalize chars in word to be ABCD (do this in a loop). Hint: use a separate ABCD (do this in a loop). Hint: use a separate variable for the element value (start with 'A')variable for the element value (start with 'A')
Declare an int array with 10 integers and Declare an int array with 10 integers and write a loop to put the value of the index into write a loop to put the value of the index into the element (e.g., intarray[3] should have the the element (e.g., intarray[3] should have the value 3)value 3)
Java Lynn Lambert CPSC150
““while” and “for” while” and “for” StructuresStructuresDr. Roberto A. FloresDr. Roberto A. Flores
CPSC 150 – Computers and Programming I
Java Lynn Lambert CPSC150
• It repeats a set of statements while a condition is true.
while ( condition ) { is TRUE execute these statements;}
““while” structureswhile” structures
Java Lynn Lambert CPSC150
““while” structureswhile” structures• It repeats a set of statements while a condition is true.
while ( condition ) { is TRUE execute these statements;}
22
11
33The dynamics of “while”
Evaluate condition: • if TRUE go to 2• If FALSE go to 3
Execute statements, and then go to 1Continue with next statement.
The dynamics of “while”Evaluate condition:
• if TRUE go to 2• If FALSE go to 3
Execute statements, and then go to 1Continue with next statement.
1.
2.3.
Java Lynn Lambert CPSC150
““while” structureswhile” 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” structureswhile” 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;
initialize variablesin conditional
initialize variablesin conditional
1
modify variablesin conditional
modify variablesin conditional
2
Java Lynn Lambert CPSC150
““while” structureswhile” 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: while” structures: ExercisesExercises
• 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: while” structures: ExercisesExercises
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: while” structures: ExercisesExercises
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” structuresfor” structures• It (also) repeats statements while a condition is true.
initialstatement
loopcondition
modifystatement
2211 44
33
55The 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 44. Modify condition variables; then go to 25. Continue with next statements.
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 44. Modify condition variables; then go to 25. Continue with next statements.
for ( ; ; ){ statements;}
Java Lynn Lambert CPSC150
Revisiting “while” Revisiting “while” exercise with “for”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: for” structures: ExercisesExercises
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…
Java Lynn Lambert CPSC150
““for” structures: for” structures: ExercisesExercises
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
ContainersContainers(ArrayList)(ArrayList)
Chapter 4Chapter 4
Java Lynn Lambert CPSC150
ArrayListArrayList Like arrays, but have built in operatorsLike arrays, but have built in operators Use library (package)Use library (package)
import java.util.ArrayList;import java.util.ArrayList; Declare variableDeclare variable
private ArrayList circles;private ArrayList circles; To create a listTo create a list
circles = new ArrayList( ); // not NOT circles = new ArrayList( ); // not NOT CircleCircle
To add an element to the list (like To add an element to the list (like Circle c)Circle c)circles.add(c)circles.add(c)
Java Lynn Lambert CPSC150
More ArrayList methodsMore ArrayList methods
To find the size:To find the size:circles.size();circles.size();
To retrieve an element:To retrieve an element:circles.get(1); //circles.get(1); // returns the second returns the second elementelement
To remove an elementTo remove an elementcircles.remove(1); circles.remove(1); // removes the second // removes the second elementelement
Java Lynn Lambert CPSC150
ArrayList loopArrayList loop for loop with indexfor loop with indexfor (int i=0;i<circles.size( ); i++)for (int i=0;i<circles.size( ); i++) circles.get(i); // this returns the ith circlecircles.get(i); // this returns the ith circle iteratorsiteratorsimport java.util.Iterator;import java.util.Iterator;for (Iterator it = circles.iterator(); for (Iterator it = circles.iterator();
it.hasNext( ); it.next( ))it.hasNext( ); it.next( )) ; ;
Remember the ()s unlike arrays
increment part of body
Java Lynn Lambert CPSC150
Chapter 6Chapter 6
TestingTesting
Java Lynn Lambert CPSC150
Testing/DebuggingTesting/Debugging
Syntax errors: Initially fixing syntax Syntax errors: Initially fixing syntax errors the hard part. After that, errors the hard part. After that, fixing logic errors:fixing logic errors:
Testing: Ensuring that your code Testing: Ensuring that your code works works
Debugging: finding where code is Debugging: finding where code is incorrectincorrect
Java Lynn Lambert CPSC150
Levels of TestingLevels of Testing
Unit testingUnit testing Application testingApplication testing
Always start at the lowest levelAlways start at the lowest level Test after every method is writtenTest after every method is written Use these tests throughout. after Use these tests throughout. after
each method, run all of the old testseach method, run all of the old tests
Java Lynn Lambert CPSC150
The good, the bad, the The good, the bad, the uglyugly
Test cases that will workTest cases that will work Test cases that will not workTest cases that will not work Test cases that should not happenTest cases that should not happen
Java Lynn Lambert CPSC150
Types of Testing (in Types of Testing (in BlueJ)BlueJ)
InspectionInspection System.out.printlnSystem.out.println Regression TestingRegression Testing
Create tests and rerun them for each new Create tests and rerun them for each new developmentdevelopment
To do that, Test Harness/Test RigTo do that, Test Harness/Test Rig Class whose sole purpose is to test another Class whose sole purpose is to test another
classclass To do that, Automatic Testing using junitTo do that, Automatic Testing using junit To do that, Record TestsTo do that, Record Tests
Java Lynn Lambert CPSC150
ExampleExample
dayday mastermindmastermind