Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert.

Similar presentations


Presentation on theme: "CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert."— Presentation transcript:

1 CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert

2 CPSC150 Java Lynn Lambert Syllabus Java Java CPSC150Lab CPSC150Lab No attendance, but Class Assignments may/may not be put on web; short turnaround No attendance, but Class Assignments may/may not be put on web; short turnaround Come see me/Java expert early and often Come see me/Java expert early and often Ask questions Ask questions Consult with (possibly non-expert) peers, but be careful. >50% of your grade is exams. Consult with (possibly non-expert) peers, but be careful. >50% of your grade is exams.

3 CPSC150 Java Lynn Lambert 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

4 CPSC150 Java Lynn Lambert A computer program: Add X to Y and store in Z In machine language: 01040100 (already simplified to decimal) 01040100 (already simplified to decimal) 01050160 01050160 04040506 04040506 02060180 02060180HUH!?

5 CPSC150 Java Lynn Lambert Assembly Each machine instruction has matching, 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!?

6 CPSC150 Java Lynn Lambert Java z=x+y; Much better! BUT, no machines understand source code. Only machine code.

7 CPSC150 Java Lynn Lambert Virtual Machine Review: Review: Computers understand machine language only Computers understand machine language only Each computer has its own language Each computer has its own language No computer understands English, Powerpoint, or Java No computer understands English, Powerpoint, or Java Java developed to be platform independent Java developed to be platform independent Virtual machine built on top of each actual machine to make all machines (windows, mac, UNIX) look alike 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” Java compiles to byte-code – not machine code, but “virtual machine code”

8 CPSC150 Java Lynn Lambert Why Java? Java is a large, complete language Java is a large, complete language Works well with web applications Works well with web applications GUIs “part” of the language GUIs “part” of the language Extensive libraries Extensive libraries (You will get C++ also) (You will get C++ also)

9 CPSC150 Java Lynn Lambert Java and BlueJ We will use BlueJ for program development We will use BlueJ for program development BlueJ runs on the Java virtual machine BlueJ 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, UNIX BlueJ is free and available for Mac, Windows, UNIX You will test and submit program using UNIX You will test and submit program using UNIX Use your Hunter Creech Account Use your Hunter Creech Account Download BlueJ for your home machines for development: www.bluej.org Download BlueJ for your home machines for development: www.bluej.org 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) (download Java first: 1.4.2 is on PCS machines): http://java.sun.com/j2se/1.4.2/download.html (Download SDK, NOT JRE) http://java.sun.com/j2se/1.4.2/download.html

10 CPSC150 Java Lynn Lambert Why BlueJ Easy to use Easy to use Object-oriented Object-oriented Start programming immediately Start programming immediately GUI, not console-based GUI, not console-based Object visualization using UML Object visualization using UML Debugger, Editor, other standard stuff Debugger, Editor, other standard stuff Simple, not for advanced applications Simple, not for advanced applications

11 CPSC150 Java Lynn Lambert Demo VNC BlueJ Shapes – compile Terms: Object, class, method, source code, parameter cp /usr/local/examples/shapes.

12 CPSC150 JavaLynn Lambert Week 2 Writing Java Code

13 CPSC150 Java Lynn Lambert Review External View External View In BlueJ main window, In BlueJ main window, Classes Classes Object bench Object bench Class relationships Class relationships Create Objects Create Objects Call/Invoke Methods of objects Call/Invoke Methods of objects

14 CPSC150 Java Lynn Lambert Source Code (Internal View) import import Comments // single line Comments // single line /* */ multiline /** */ Javadoc Class definitions Class definitions public class Picture { // fields // constructors // methods }

15 CPSC150 Java Lynn Lambert Class details: fields/attributes Lifetime/scope of class Lifetime/scope of class private int myfield; // primitive private int myfield; // primitive char, boolean, double, a few others char, boolean, double, a few others private String mystring; // class private String mystring; // class private Circle sun; private Circle sun; user and library defined user and library defined BlueJ: primitive has data; object has pointer BlueJ: primitive has data; object has pointer Clock example, ClockDisplay, NumberDisplay Clock example, ClockDisplay, NumberDisplay

16 CPSC150 Java Lynn Lambert Class details: constructors Initialize objects. Called when object is created Initialize objects. Called when object is created no return type no return type can be overloaded can be overloaded public Circle() { diameter = 30; xPosition = 20; yPosition = 60; color = "blue"; isVisible = false; } public Circle(int d, int x, int y, color c) { diameter = d; xPosition = x; yPosition = y; color = c; isVisible = false; }

17 CPSC150 Java Lynn Lambert Class Details: Methods General Structure: General Structure: public/private return-type name (param1name param1type, param2name param2type) changeColor method from Circle: changeColor method from Circle: public void changeColor(String newColor) public void changeColor(String newColor) { color = newColor; 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

18 CPSC150 Java Lynn Lambert Method vs. Field Both have private or public Both have private or public Both have types Both have types Both have names Both have names fields have ‘;’ at end of line/methods do not fields have ‘;’ at end of line/methods do not methods have () (even without parameters); fields do not methods have () (even without parameters); fields do not methods have a body; fields do not methods have a body; fields do not fields have memory to hold information; methods do not fields have memory to hold information; methods do not

19 CPSC150 Java Lynn Lambert Field vs. Local variable local variables declare in a method; fields outside of all methods local variables declare in a method; fields outside of all methods local variables have the lifetime of the method call local variables have the lifetime of the method call local variables and fields have type and ‘;’ local variables and fields have type and ‘;’ local variables do NOT have private/public designation local variables do NOT have private/public designation

20 CPSC150 Java Lynn Lambert Writing methods: More Java statements Arithmetic Expressions Arithmetic Expressions Compound Assignment Compound Assignment System.out.println System.out.println this this new new dot notation dot notation return return

21 CPSC150 Java Lynn Lambert Arithmetic +, /, *, -, % +, /, *, -, % Codepad (Choose view, then codepad) Codepad (Choose view, then codepad) Be careful about integer division Be careful about integer division 4/3  r 3 4/3  r 3

22 CPSC150 Java Lynn Lambert Compound Assignment assignment: assignment: answer = factor1 * factor2; answer = factor1 * factor2; answer = answer + newsum; answer = answer + newsum; compound assignment compound assignment answer += newsum; answer += newsum; answer -= diff; answer -= diff; answer *= product; // e.g., factorial answer *= product; // e.g., factorial answer /= digit; // getting rid of digits answer /= digit; // getting rid of digits answer %= digit; answer %= digit; Use codepad Use codepad int answer=30; answer %= 4; System.out.println("Answer is " + answer); int answer=30; answer %= 4; System.out.println("Answer is " + answer);

23 CPSC150 Java Lynn Lambert System.out.println() To print out messages to a terminal To print out messages to a terminal Can print strings or integers Can print strings or integers Use + to concatenate/append. Be careful with numbers Use + to concatenate/append. Be careful 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 + answer); System.out.println(“answer is” + answer + answer);

24 CPSC150 Java Lynn Lambert this public void changeColor(String newColor) { color = newColor; draw(); } public void changeColor(String color) { this.color = color; draw(); } this specifies the current object

25 CPSC150 Java Lynn Lambert new, dot notation public void draw() public void draw() { 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 } To create a new object, use new. calls constructor Extermal method call dot notation

26 CPSC150 Java Lynn Lambert return statement public int sum(int x, int y) { int answer; int answer; answer = x+y; return answer; } type of method is return type to return a value, use ‘return value’; can be calculation

27 CPSC150 Java Lynn Lambert Common Methods to Write Wizard at writing code; let’s look at common methods Wizard at writing code; let’s look at common methods Mutator method: change value of a field Mutator method: change value of a field e.g., setTime in Clock e.g., setTime in Clock Accessor method: get the value of a field Accessor method: get the value of a field e.g., getTime in Clock e.g., getTime in Clock

28 CPSC150 Java Lynn Lambert Common methods: Accessor Retrieve the value of a field Retrieve the value of a field no parameter, return type is type of field no parameter, return type is type of field method body is one line method body is one line public class fraction { // only a little bit defined private int numerator; private int numerator; private int denominator; private int denominator; public int GetNum() { return numerator; }}

29 CPSC150 Java Lynn Lambert Common Method: mutator Changes field value Changes field value void return type, one parameter is new value void return type, one parameter is new value not all fields have to have mutator methods not all fields have to have mutator methods public class fraction {// only a portion of this class private int numerator; private int numerator; private int denominator; private int denominator; public void SetNum(int newvalue) { numerator = newvalue; }}

30 CPSC150 Java Lynn Lambert Conditionals Execute code under some conditions Execute code under some conditions In Canvas In Canvas public static Canvas getCanvas() { // only create Canvas if not already created if (canvasSingleton == null) { if (canvasSingleton == null) { canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, Color.white); Color.white);} canvasSingleton.setVisible(true); canvasSingleton.setVisible(true); return canvasSingleton; return canvasSingleton;}

31 CPSC150 Java Lynn Lambert if statements if (booleanexpression) java statement; java statement; any Java statement you know about we don’t know about this

32 CPSC150 Java Lynn Lambert Boolean Expressions Evaluate to be true or false Evaluate to be true or false boolean variables boolean variables boolean isVisible = false; boolean isVisible = false; relational expressions (compares values) relational expressions (compares values) logical expressions (compares expressions with and, or, not) logical expressions (compares expressions with and, or, not)

33 CPSC150 Java Lynn Lambert Relational Operators for primitives int x, y; x < y x < y x <= y x <= y x > y x > y x >= y x >= y x != y x != y x == y // NOT x=y x == y // NOT x=y NOTE: most of these don’t work for classes (== is a problem) NOTE: most of these don’t work for classes (== is a problem)

34 CPSC150 Java Lynn Lambert Evaluating Boolean Expressions int x=3; int y = 4; int z=5; x < y x < y < z x = y y == 4 z >= x x != 3 (x + 4) < (y - 1) true error: < cannot be applied to boolean,int error: incompatible types - found int; expected boolean true false false 7 < 3; false

35 CPSC150 Java Lynn Lambert Logical Operators and (&&, single & very different) and (&&, single & very different) both values must be true for the expression to be true 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) if it is cold and rainy, wear your winter raincoat (both must be true) or (|| - on keyboard, called pipe symbol) or (|| - on keyboard, called pipe symbol) either value can be true either value can be true if it is cold or rainy, wear a coat (if either or both is true, do) if it is cold or rainy, wear a coat (if either or both is true, do) not (!) not (!) changes the truth value of the expression changes the truth value of the expression if it is not cold, do not wear a winter coat if it is not cold, do not wear a winter coat

36 CPSC150 Java Lynn Lambert Logical Operators int x=3; int y=10; (x < y) && (y < 20) (x == 3) || (y == 3) 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)

37 CPSC150 Java Lynn Lambert More logical operators int x=3; int y=10; !(y=10) (x != 3) || (y != 3) trick question error !(y==10) y == 10 true !true false x != 3 false Keep going. y != 3 true false || true is true

38 CPSC150 Java Lynn Lambert Yet more logical operators int x=3; int y=10; !((x+1 < 4) || (y <= 10)) !((x+1 < 4) && (y <= 10)) 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

39 CPSC150 Java Lynn Lambert Strings and Classes == 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 == 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 use equals no corresponding <, lessthan,… no corresponding <, lessthan,… use compareTo use compareTo

40 CPSC150 Java Lynn Lambert CompareTo Returns 0 if 2 Strings are equal Returns 0 if 2 Strings are equal Returns negative number if object<parameter Returns negative number if object<parameter Returns positive number if object > parameter Returns positive number if object > parameter

41 CPSC150 Java Lynn Lambert 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) System.out.println(“s1 less than s2”); System.out.println(“s1 less than s2”); 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 < lowercase System.out.println(“s2 less than s3”); System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”); System.out.println(“s3 less than s2”); // will print // will not print // will print // will not print

42 CPSC150 Java Lynn Lambert 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”); System.out.println(“s1 is the same as s2”); 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)) 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) System.out.println(“s3 is the same as s2”); System.out.println(“s3 is the same as s2”); if (s1 == s2) System.out.println(“s1 and s2 point to the same object”); System.out.println(“s1 and s2 point to the same object”); // will not print // will print; symmetric // will print // will not print // compareTo == 0 is same as equals

43 CPSC150 Java Lynn Lambert if statements if statement form: if statement form: if (boolean expression) if (boolean expression) java statement; java statement; if (x < y) System.out.println(“x < y”); System.out.println(“x < y”); you know both parts now

44 CPSC150 Java Lynn Lambert if statements cautions MUST have ()s around boolean expression MUST have ()s around boolean expression no syntax error for non-boolean like expressions no syntax error for non-boolean like expressions only ONE statement in an if statement only ONE statement in an if statement no ';' after if condition no ';' after if condition Make sure you account for values that are equal Make sure you account for values that are equal use relational operators only with primitives use relational operators only with primitives use equals, compareTo with String use equals, compareTo with String

45 CPSC150 Java Lynn Lambert if-else If you want to do one thing if a condition is true and something else if not, use 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) form: if (condition) Java statement Java statement else else Java statement Java statement if (x < y) System.out.println(x + " is less than the other number”); System.out.println(x + " is less than the other number”);else System.out.println(y + " is less than the other number”); System.out.println(y + " is less than the other number”);

46 CPSC150 Java Lynn Lambert > 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; x = 0; } else else { System.out.println(y + " is less than the other number”); System.out.println(y + " is less than the other number”); y = 0; y = 0; }

47 CPSC150 Java Lynn Lambert If-else cautions either if clause or else clause or both may have {}s. 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 After statements inside if and else clause are executed, control passes back to next sequential statement no ';' after else no ';' after else Make sure you account for values that are equal Make sure you account for values that are equal

48 CPSC150 Java Lynn Lambert Class Work Write an if statement to assign x to y if x is greater than y Write an if statement to assign x to y if x is greater than y Consider a class 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

49 CPSC150 Java Lynn Lambert Watch Out if (3 < 4) x = 3; x = 3;else System.out.println(“3 < 4 is false”); System.out.println(“3 < 4 is false”); x = 0; x = 0; System.out.println( "the value of x is " + x);

50 CPSC150 Java Lynn Lambert Embedded ifs If statements and if-else statements may be embedded (if within if). simply evaluate them as the Java code is executed: 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 if-else example is most common. sets up a table of conditions

51 CPSC150 Java Lynn Lambert Embedded if-else for table if (ave >= 90) grade = 'A'; grade = 'A'; else if ((ave = 80)) // note: need ()s around entire condition // note: need ()s around entire condition grade = 'B'; grade = 'B'; else if ((ave =70)) grade = 'C'; grade = 'C'; else if ((ave =60)) grade = 'D'; grade = 'D'; else if ((ave < 70) && (ave < 60)) grade = 'F'; grade = 'F';

52 CPSC150 Java Lynn Lambert Tracing through the embedded if

53 CPSC150 Java Lynn Lambert Fixing the embedded if if (ave >= 90) grade = 'A'; grade = 'A'; else if (ave >= 80) // We know (ave < 90) or we wouldn't be here grade = 'B'; grade = 'B'; else if (ave >=70) // we know ave =70) // we know ave < 80 grade = 'C'; grade = 'C'; else if (ave >=60) grade = 'D'; grade = 'D';else // if ((ave < 70) && (ave < 60)) grade = 'F'; grade = 'F';

54 CPSC150 Java Lynn Lambert Cautions for embedded ifs Don't use redundant comparisons Don't use redundant comparisons Make sure you check for values that are equal Make sure you check for values that are equal Account for out of range values Account for out of range values

55 CPSC150 Java Lynn Lambert Program style Put {}s on a line by themselves Put {}s on a line by themselves indent {}s 2-3 spaces, statements one more than that indent {}s 2-3 spaces, statements one more than that All code outside if statements should line up All code outside if statements should line up All code inside of if statements should line up. All code inside of if statements should line up.

56 CPSC150 Java Lynn Lambert More complicated embedded ifs if (x < 3) if (y < 6) if (y < 6) System.out.println( "x and y between 3 and 6"); System.out.println( "x and y between 3 and 6"); else else System.out.println( "x = 6"); System.out.println( "x = 6");else if (y > 6) if (y > 6) System.out.println( "x and y not in 3-6 range"); System.out.println( "x and y not in 3-6 range"); else else System.out.println( "x >= 3); y = 3); y <= 6 ");

57 CPSC150 JavaLynn Lambert Arrays and Loops week 4 Chapter 4

58 CPSC150 Java Lynn Lambert Each variable only holds one item Each variable only holds one item if > 1 item wanted, need an array if > 1 item wanted, need an array array that holds a word array that holds a word arrays hold elements all of the same type arrays hold elements all of the same type char[ ] word = new char[4]; holds 4 elements of type char holds 4 elements of type char Arrays 0132 word

59 CPSC150 Java Lynn Lambert char[ ] word = new char[4]; two parts to an array: index -- integer element – type inside array 'h''e' 0132 'h' 0132 word[1] = 'e'; 'h''e''o''r' 0132 'h''e''o' 0132 word[3] = 'o'; word[2] = 'r'; word[0] = 'h';

60 CPSC150 Java Lynn Lambert Can use variables for index OR elements Can use variables for index OR elements int i=3; char new = 'd'; word[i] = new; can find length can find length word.length // is 4 largest index is always length – 1 largest index is always length – 1 word[4] is RUN time error word[4] is RUN time error Array manipulation 'h''e''o''r' 0132 'h''e''d''r' 0132

61 CPSC150 Java Lynn Lambert arrays and new char[ ] word; creates word that is of type char array that points to nothing 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) creates array of 4 elements initialized to \u0000 (Java always initializes primitives to 0)

62 CPSC150 Java Lynn Lambert Myarray example public class Myarray { private static Circle[] circles; private static Circle[] circles; private static double[] area; private static double[] area; // other stuff in the class }

63 CPSC150 Java Lynn Lambert Myarray gets elements allocated Create an object Create an object circles = new Circle[4]; circles = new Circle[4]; area = new double[4]; area = new double[4];

64 CPSC150 Java Lynn Lambert createcircles() createcircles() createcircles() circles[0] = new Circle();

65 CPSC150 Java Lynn Lambert array creation summary char[ ] word; char[ ] word; creates a space named word that contains null word = new char [4]; word = new char [4]; allocates 4 chars, initialized, word points to them classes: Circle[ ] mycircles; classes: Circle[ ] mycircles; same as word mycircles = new Circle[4]; mycircles = new Circle[4]; allocates 4 spaces that contain null mycircles[0] = new Circle( ); mycircles[0] = new Circle( ); creates an actual circle

66 CPSC150 Java Lynn Lambert Repetition in arrays arrays often do the same thing arrays often do the same thing (e.g., for each Circle in array, create a Circle) for (int i=0; i<circles.length; i++) circles[i] = new Circle( ); circles[i] = new Circle( ); memorize this line

67 CPSC150 Java Lynn Lambert Do: In a group 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 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') 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) 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)

68 CPSC150 JavaLynn Lambert “while” and “for” Structures Dr. Roberto A. Flores CPSC 150 – Computers and Programming I

69 CPSC150 Java Lynn Lambert It repeats a set of statements while a condition is true. while ( condition ) { is TRUE execute these statements; } “while” structures

70 CPSC150 Java Lynn Lambert “while” structures It repeats a set of statements while a condition is true. while ( condition ) { is TRUE execute these statements; } 2 2 1 1 3 3 The dynamics of “while” Evaluate condition: if TRUE go to 2 If FALSE go to 3 Execute statements, and then go to 1 Continue 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 1 Continue with next statement. 1. 2. 3.

71 CPSC150 Java Lynn Lambert “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?

72 CPSC150 Java Lynn Lambert “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; initialize variables in conditional initialize variables in conditional 1 modify variables in conditional modify variables in conditional 2

73 CPSC150 Java Lynn Lambert “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);

74 CPSC150 Java Lynn Lambert “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 ); }

75 CPSC150 Java Lynn Lambert “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).

76 CPSC150 Java Lynn Lambert “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).

77 CPSC150 Java Lynn Lambert “for” structures It (also) repeats statements while a condition is true. initial statement loop condition modify statement 2 2 1 1 4 4 3 3 5 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. 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. for ( ; ; ) { statements; }

78 CPSC150 Java Lynn Lambert 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; }

79 CPSC150 Java Lynn Lambert “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…

80 CPSC150 Java Lynn Lambert “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!

81 CPSC150 JavaLynn Lambert Containers (ArrayList) Chapter 4

82 CPSC150 Java Lynn Lambert ArrayList Like arrays, but have built in operators Like arrays, but have built in operators Use library (package) Use library (package) import java.util.ArrayList; Declare variable Declare variable private ArrayList circles; To create a list To create a list circles = new ArrayList( ); // not NOT Circle To add an element to the list (like Circle c) To add an element to the list (like Circle c)circles.add(c)

83 CPSC150 Java Lynn Lambert More ArrayList methods To find the size: To find the size:circles.size(); To retrieve an element: To retrieve an element: circles.get(1); // returns the second element To remove an element To remove an element circles.remove(1); // removes the second element

84 CPSC150 Java Lynn Lambert ArrayList loop for loop with index for loop with index for (int i=0;i<circles.size( ); i++) circles.get(i); // this returns the ith circle circles.get(i); // this returns the ith circle iterators iterators import java.util.Iterator; for (Iterator it = circles.iterator(); it.hasNext( ); it.next( )) it.hasNext( ); it.next( )) ; Remember the ()s unlike arrays increment part of body

85 CPSC150 JavaLynn Lambert Chapter 6 Testing

86 CPSC150 Java Lynn Lambert Testing/Debugging Syntax errors: Initially fixing syntax errors the hard part. After that, fixing logic errors: Testing: Ensuring that your code works Testing: Ensuring that your code works Debugging: finding where code is incorrect Debugging: finding where code is incorrect

87 CPSC150 Java Lynn Lambert Levels of Testing Unit testing Unit testing Application testing Application testing Always start at the lowest level Always start at the lowest level Test after every method is written Test after every method is written Use these tests throughout. after each method, run all of the old tests Use these tests throughout. after each method, run all of the old tests

88 CPSC150 Java Lynn Lambert The good, the bad, the ugly Test cases that will work Test cases that will work Test cases that will not work Test cases that will not work Test cases that should not happen Test cases that should not happen

89 CPSC150 Java Lynn Lambert Types of Testing (in BlueJ) Inspection Inspection System.out.println System.out.println Regression Testing Regression Testing Create tests and rerun them for each new development Create tests and rerun them for each new development To do that, Test Harness/Test Rig To do that, Test Harness/Test Rig Class whose sole purpose is to test another class Class whose sole purpose is to test another class To do that, Automatic Testing using junit To do that, Automatic Testing using junit To do that, Record Tests To do that, Record Tests

90 CPSC150 Java Lynn Lambert Example day day mastermind mastermind


Download ppt "CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert."

Similar presentations


Ads by Google