Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert.

Similar presentations


Presentation on theme: "CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert."— Presentation transcript:

1 CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert

2 CPSC150 JavaDr. L. Lambert Week 1 Chapter 1 Java, BlueJ, Objects, Terms

3 CPSC150 Java Dr. L. Lambert Syllabus Java Java CPSC150Lab CPSC150Lab Attendance, but does not count Attendance, but does not count weekly quiz. Due the next week. Graded. Collaborative. Come prepared to work on it in class. weekly quiz. Due the next week. Graded. Collaborative. Come prepared to work on it in class. 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.

4 CPSC150 Java Dr. L. Lambert Quiz: week 1 Using the Shapes example, draw a snowman in BlueJ (by creating objects and modifying them) that looks like this (exact dimensions and placement are not important). Using the Shapes example, draw a snowman in BlueJ (by creating objects and modifying them) that looks like this (exact dimensions and placement are not important). Capture the image and window with the object bench (yours will not be empty as this one is) Capture the image and window with the object bench (yours will not be empty as this one is) Print source code for one Class (e.g., Circle) Print source code for one Class (e.g., Circle) Identify in these three at least one of each of the following: object, Class, method call, parameter, instance, method (definition), signature, type, source code, return value Identify in these three at least one of each of the following: object, Class, method call, parameter, instance, method (definition), signature, type, source code, return value Turn in a printed copy of: captured image, captured BlueJ window, source code for one Class. Terms should be identified on each as appropriate. Turn in a printed copy of: captured image, captured BlueJ window, source code for one Class. Terms should be identified on each as appropriate.

5 CPSC150 Java Dr. L. 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”

6 CPSC150 Java Dr. L. 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 (Other CS courses will cover C++) (Other CS courses will cover C++)

7 CPSC150 Java Dr. L. 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

8 CPSC150 Java Dr. L. Lambert Using 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.orgwww.bluej.org (download Java 1.5 first): http://java.sun.com/j2se/1.5.0/download.jsp (Download SDK, NOT JRE) (download Java 1.5 first): http://java.sun.com/j2se/1.5.0/download.jsp (Download SDK, NOT JRE)

9 CPSC150 Java Dr. L. Lambert UseBlueJ on Suns in Hunter Creech on Macs in G115 on your own computer (programs submitted on UNIX/Hunter Creech accounts) Demo: Shapes – bluej import, compile Terms: object (on object bench and in source code), class, instance, method (definition), method call, return value, parameter, source code, signature (in source code and external view), formal parameter, actual parameter, type cp /usr/local/examples/shapes. Looking at an Example: External View (dot MUST be there)

10 CPSC150 JavaDr. L. Lambert Reading and Writing Java Code Weeks 1 and 2 Chapters 1 and 2

11 CPSC150 Java Dr. L. Lambert Quiz: week 2 (= you know enough to do Quiz 1) Print Picture.java from the BlueJ examples folder. Print Picture.java from the BlueJ examples folder. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. Add by hand three methods: Add by hand three methods: in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write an accessor method getSize that returns the value of diameter in Circle.java, write an accessor method getSize that returns the value of diameter in Circle.java, write a mutator method setPosition that takes two int parameters that represent the new x and y position of the circle. If x >= 0 and = 0 and = 0 and = 0 and <= 300, change XPosition and YPosition to be the values in the parameters and redraw the Circle. Otherwise, do nothing. Start this by coding it without the if.

12 CPSC150 Java Dr. L. 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

13 CPSC150 Java Dr. L. 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 }

14 CPSC150 Java Dr. L. Lambert Class details: fields/instance variables Lifetime/scope of class Lifetime/scope of class field vs local variable field vs local variable 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 (Inspect object in /home/lambert/Public/projects/chapter03/clock-display)

15 CPSC150 Java Dr. L. 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 }

16 CPSC150 Java Dr. L. 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( ) { // give fields default values { // give fields default values diameter = 30; xPosition = 20; yPosition = 60; color = "blue"; isVisible = false; } public Circle(int d, int x, int y, color c) { // give fields client-specified values { // give fields client-specified values diameter = d; xPosition = x; yPosition = y; color = c; isVisible = false; }

17 CPSC150 Java Dr. L. Lambert Work on Quiz Time Print Picture.java from the BlueJ examples folder. Print Picture.java from the BlueJ examples folder. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. Add by hand three methods: Add by hand three methods: in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write an accessor method getSize that returns the value of diameter in Circle.java, write a mutator method setPosition that takes two int parameters that represent the new x and y position of the circle. If x >= 0 and = 0 and <= 300, change XPosition and YPosition to be the values in the parameters and redraw the Circle. Otherwise, do nothing. Start this by coding it without the if.

18 CPSC150 Java Dr. L. 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 } writing a method methods vs fields vs local variables Java statements accessor/mutator methods

19 CPSC150 Java Dr. L. 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 (visible in external view also) Java statements inside body, e.g., single = assignment curly braces, stuff inside is method body formal parameter Internal method call Method call (with actual parameters if necessary)

20 CPSC150 Java Dr. L. 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

21 CPSC150 Java Dr. L. 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 ‘;’ when possible, use local variables when possible, use local variables local variables do NOT have private/public designation local variables do NOT have private/public designation

22 CPSC150 Java Dr. L. 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: external method calls dot notation: external method calls return return

23 CPSC150 Java Dr. L. Lambert Arithmetic +, /, *, -, % +, /, *, -, % Be careful about integer division Be careful about integer division 4/3  r 3 4/3  r 3 Use codepad (Choose view, then codepad) Use codepad (Choose view, then codepad) int answer=30; answer %= 4; System.out.println("Answer is " + answer); int answer=30; answer %= 4; System.out.println("Answer is " + answer);

24 CPSC150 Java Dr. L. 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;

25 CPSC150 Java Dr. L. Lambert Math Problems Do on board int x=3; double y=4.0; int x=3; double y=4.0;x+yx/2y/3x%2x%3

26 CPSC150 Java Dr. L. 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);

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

28 CPSC150 Java Dr. L. 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 External method call dot notation

29 CPSC150 Java Dr. L. Lambert Quiz Work Print Picture.java from the BlueJ examples folder. Print Picture.java from the BlueJ examples folder. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. Add by hand three methods: Add by hand three methods: in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write an accessor method getSize that returns the value of diameter in Circle.java, write a mutator method setPosition that takes two int parameters that represent the new x and y position of the circle. If x >= 0 and = 0 and <= 300, change XPosition and YPosition to be the values in the parameters and redraw the Circle. Otherwise, do nothing. Start this by coding it without the if.

30 CPSC150 Java Dr. L. 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

31 CPSC150 Java Dr. L. 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

32 CPSC150 Java Dr. L. 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() public int getNum() { return numerator; return numerator; }}

33 CPSC150 Java Dr. L. 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) public void setNum(int newvalue) { numerator = newvalue; numerator = newvalue; }}

34 CPSC150 Java Dr. L. Lambert Work on Quiz 2 Print Picture.java from the BlueJ examples folder. Print Picture.java from the BlueJ examples folder. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12. Add by hand three methods: Add by hand three methods: in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would be, or code it, then write it down). in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the Yposition field to the second in Circle.java, write an accessor method getSize that returns the value of diameter in Circle.java, write a mutator method setPosition that takes two int parameters that represent the new x and y position of the circle. If x >= 0 and = 0 and <= 300, change XPosition and YPosition to be the values in the parameters and redraw the Circle. Otherwise, do nothing. Start this by coding it without the if.

35 CPSC150 Java Dr. L. Lambert Class Work Write a Student class that has two fields, name (of type String) and GPA (of type double). write accessor and mutator methods for ONE of these fields. Write a print method that prints the fields in the class. Show your answer to 1-2 others, then write it on the board. printing is usually done with toString method which returns a reasonable String representation of the class. Write toString definition on the board. printing is usually done with toString method which returns a reasonable String representation of the class. Write toString definition on the board. Change print to call toString Change print to call toString Write a Class Course that has two students (student1 and student2). Print out student1’s and student2’s info. Write a Class Course that has two students (student1 and student2). Print out student1’s and student2’s info. but don’t sit down yet

36 CPSC150 Java Dr. L. Lambert Quiz: Week 3 Create a new project that has a Student class with two fields: name (a String) and GPA (a double). Create a new project that has a Student class with two fields: name (a String) and GPA (a double). Write accessor, mutator and toString methods for the class. Write accessor, mutator and toString methods for the class. Create two students on the object bench, and use the appropriate methods to assign values. With inspect, show the values. Capture the inspector window and print it. Create two students on the object bench, and use the appropriate methods to assign values. With inspect, show the values. Capture the inspector window and print it. Write another class in the same project, Course, that has two Student fields. In the Course class constructor, create two students and give values to the names and GPA. Have another method toString that returns each student on a separate line (use “\n” to put a new line in a string). Write another class in the same project, Course, that has two Student fields. In the Course class constructor, create two students and give values to the names and GPA. Have another method toString that returns each student on a separate line (use “\n” to put a new line in a string). Create a Course object; call the toString method, and capture the window that shows the console with the two students names. Print the captured console window. Create a Course object; call the toString method, and capture the window that shows the console with the two students names. Print the captured console window. Print the Student and Course source code. Print the Student and Course source code.

37 CPSC150 Java Dr. L. 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); // does this no matter what canvasSingleton.setVisible(true); // does this no matter what return canvasSingleton; return canvasSingleton;}

38 CPSC150 Java Dr. L. Lambert if statements if (booleanexpression) java statement; java statement; any Java statement you know about we don’t know about this

39 CPSC150 Java Dr. L. 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)

40 CPSC150 Java Dr. L. 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)

41 CPSC150 Java Dr. L. Lambert Evaluating Boolean Expressions Do on board with partners 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

42 CPSC150 Java Dr. L. 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

43 CPSC150 Java Dr. L. Lambert Logical Operators Do on board 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)

44 CPSC150 Java Dr. L. Lambert More logical operators Do on board 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

45 CPSC150 Java Dr. L. Lambert Yet more logical operators Do on board 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

46 CPSC150 Java Dr. L. 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 Difference between primitives (holds a value) and Classes (holds a pointer) is important. Difference between primitives (holds a value) and Classes (holds a pointer) is important. = is for comparing if values are the same = is for comparing if values are the same

47 CPSC150 Java Dr. L. 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

48 CPSC150 Java Dr. L. Lambert compareTo code write on board what will print 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

49 CPSC150 Java Dr. L. Lambert More String comparisions on board 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”); (done with board work) // will not print // will print; symmetric // will print // will not print // compareTo == 0 is same as equals

50 CPSC150 Java Dr. L. 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

51 CPSC150 Java Dr. L. 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

52 CPSC150 Java Dr. L. 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”);

53 CPSC150 Java Dr. L. 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; }

54 CPSC150 Java Dr. L. 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

55 CPSC150 Java Dr. L. 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

56 CPSC150 Java Dr. L. 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); Prints what?

57 CPSC150 Java Dr. L. 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

58 CPSC150 Java Dr. L. 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';

59 CPSC150 Java Dr. L. Lambert Tracing through the embedded if

60 CPSC150 Java Dr. L. 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';

61 CPSC150 Java Dr. L. 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

62 CPSC150 Java Dr. L. 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.

63 CPSC150 Java Dr. L. 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 "); Write on board output for: (1) x is 3 and y is 6; (2) x is 0 and y is 0; (3) x is 0 and y is 6; (4) x is 99 and y is 6


Download ppt "CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert."

Similar presentations


Ads by Google