Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC150 Spring 2006 Dr. L Lambert. Week 1/2 intro (and Chapter 1)

Similar presentations


Presentation on theme: "CPSC150 Spring 2006 Dr. L Lambert. Week 1/2 intro (and Chapter 1)"— Presentation transcript:

1 CPSC150 Spring 2006 Dr. L Lambert

2 Week 1/2 intro (and Chapter 1)

3 Syllabus Java CPSC150Lab Attendance, but does not count weekly quiz. Due the next week. Graded. Collaborative. Come prepared to work on it in class. Come see me/Java expert early and often Ask questions Consult with (possibly non-expert) peers, but be careful. >50% of your grade is exams.

4 Virtual Machine Review: –Computers understand machine language only –Each computer has its own language –No computer understands English, Powerpoint, or Java Java developed to be platform independent –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”

5 Why Java? Java is a large, complete language Works well with web applications GUIs “part” of the language Extensive libraries (Other CS courses will cover C++)

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

7 Using Java and BlueJ We will use BlueJ for program development BlueJ runs on the Java virtual machine BlueJ is IDE – lots of others (e.g., Eclipse) BlueJ is free and available for Mac, Windows, UNIX You will test and submit program using UNIX Use your Hunter Creech Account Download BlueJ for your home machines for development: www.bluej.orgwww.bluej.org (download Java 1.5 first): http://java.sun.com/j2se/1.5.0/download.jsp (Download SDK, NOT JRE)

8 Reading and Writing Java Code Weeks 1 and 2 Chapters 1 and 2

9 By the end of this week, you should know how to: Write a Java program Use BlueJ to write and run a Java program Call methods from inside a program and from the object bench Use parameters in method definitions and method calls Use instance variables/fields Create constructors Write assignment statements Write mathematical expressions

10 object (on object bench and in source code) class, instance default constructor, overloading method (definition) method call return value parameter source code signature (in source code and external view) formal parameter actual parameter type Terms on test 1

11 Writing a Java program // import statements if any public class Name { // instance variables or fields // visible to all methods in class // constructors. with no parameters is Default // methods }

12 /** starts javadoc. TimesTable performs multiplication/times table */ public class TimesTable // NO ( ) s in class { private int factor; // field /** have javadoc for every class, constructor and method * Constructor. without parameter, called default constructor. no return type */ // return type void because nothing is returned public void TimesTable(int nbr) // actual parameter has type AND name { factor = nbr; // assignment statement } public int times(int nbr) // return type int { return nbr * factor; // math } // other methods go in here. printTimes(int nbr) and printTable( ) }

13 Do your own On the board, with 1 or 2 others, write: printTimes(int nbr) printTable( )

14 // insert these methods into class on previous slide public void printTimes(int nbr) { // System.out.println changes System.out.println(factor + " times " + nbr + " is " + times(nbr)); } public void printTable( ) // methods start with lowercase { printTimes(0); printTimes(1); printTimes(2); printTimes(3); printTimes(4); printTimes(5); printTimes(6); printTimes(7); printTimes(8); printTimes(9); }

15 Class Details Using bluej Using methods Fields/instance variables constructors methods

16 Class details: fields/instance variables Lifetime/scope of class –field vs local variable private int myfield; // primitive –char, boolean, double, a few others private String mystring; // class private Circle sun; // from Shapes –user and library defined BlueJ: primitive has data; object has pointer

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

18 Class details: constructors Initialize objects. Called when object is created no return type can be overloaded public void TimesTable (int nbr) { factor = nbr; factor = nbr;} public void TimesTable ( ) { factor = 1; factor = 1;}

19 Source Code (Internal View) import Comments // single line /* */ multiline /** */ Javadoc Class definitions public class Picture { // fields // constructors // methods } writing a method methods vs fields vs local variables Java statements accessor/mutator methods

20 Class Details: Methods General Structure: public/private return-type name (param1name param1type, param2name param2type) times method from TimesTable: public int times(int nbr) { int answer; answer = nbr * factor; return answer; } return type int 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 return statement formal parameter list: type AND name Local variabl e

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

22 Field vs. Local variable local variables declare in a method; fields outside of all methods local variables have the lifetime of the method call local variables and fields have type and ‘;’ when possible, use local variables local variables do NOT have private/public designation

23 Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println this new dot notation: external method calls return

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

25 Compound Assignment assignment: –answer = factor1 * factor2; –answer = answer + newsum; compound assignment –answer += newsum; –answer -= diff; –answer *= product; // e.g., factorial –answer /= digit; // getting rid of digits –answer %= digit;

26 Math Problems Do on board int x=3; double y=4.0; x + y x / 2 y / 3 x % 2 x % 3

27 System.out.println( ) To print out messages to a terminal Can print strings or integers Use + to concatenate/append. Be careful with numbers e.g., –System.out.println("Answer is " + answer); –System.out.println(answer + answer); –System.out.println(“answer is” + answer + answer);

28 this public void changeColor(String newColor) { color = newColor; draw( ); } public void changeColor(String color) { this.color = color; draw( ); } this specifies the current object

29 new, dot notation public void draw() { wall = new Square( ); wall.moveVertical(80); wall.changeSize(100); wall.makeVisible(); //rest of method from Picture class } To create a new object, use new. calls constructor External method call dot notation

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

31 Another Java Example: Picture.java public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; public Picture() { // nothing to do... instance variables are automatically set to null } // other methods }

32 Picture.java public void draw( ) { wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(20); window.moveVertical(100); window.makeVisible(); roof = new Triangle(); roof.changeSize(50, 140); roof.moveHorizontal(60); roof.moveVertical(70); roof.makeVisible(); sun = new Circle(); // set sun to be where it should be }

33 Picture.java Constructor: –now: blank canvas like TV show –one option: create a finished picture –another option: create shapes, then put them on Modify to do second option

34 Picture.java On the board, write a new constructor and a new draw( ) that creates the shapes, then puts them on

35 More Picture.java on the board Write a new constructor in Circle.java that allows Circles to be created in the right place with the right color. For example, instead of // old sun = new Circle( ); sun.changeColor("yellow"); sun.moveHorizontal(180); sun.moveVertical(-10); sun.changeSize(60); sun.makeVisible( ); // new // xPosition = 180 + 20; // yPosition = 60-10 sun = new Circle("yellow", 60, 200, 50); sun.makeVisible( );

36 Common Methods to Write Wizard at writing code; let’s look at common methods Mutator method: change value of a field Accessor method: get the value of a field

37 Common methods: Accessor Retrieve the value of a part of a class, often a field no parameter, return type is type of value being returned method body is (often) one line public class Fraction { // only a little bit defined private int numerator; private int denominator; public int getNum() { return numerator; }

38 Common Method: mutator Changes field value void return type, one parameter, the new value not all fields have mutator methods public class fraction {// only a portion of this class private int numerator; private int denominator; public void setNum(int newvalue) { numerator = newvalue; }

39 Do on board Write a setFactor and a getFactor method

40 Conditionals

41 Execute code under some conditions In Canvas public static Canvas getCanvas() { // only create Canvas if not already created if (canvasSingleton == null) { canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, Color.white); } canvasSingleton.setVisible(true); // does this no matter what return canvasSingleton; }

42 if statements if (booleanexpression) java statement; any Java statement you know about we don’t know about this

43 Boolean Expressions Evaluate to be true or false boolean variables –boolean isVisible = false; relational expressions (compares values) logical expressions (compares expressions with and, or, not)

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

45 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

46 Logical Operators and (&&, single & very different) –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) or (|| - on keyboard, called pipe symbol) –either value can be true –if it is cold or rainy, wear a coat (if either or both is true, do) not (!) –changes the truth value of the expression –if it is not cold, do not wear a winter coat

47 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)

48 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

49 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

50 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 use equals no corresponding <, lessthan,… use compareTo Difference between primitives (holds a value) and Classes (holds a pointer) is important. = is for comparing if values are the same

51 CompareTo Returns 0 if 2 Strings are equal Returns negative number if object<parameter Returns positive number if object > parameter

52 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”); if (s2.compareTo(s1) < 0) System.out.println(“s2 less than s1”); if (s2.compareTo(s3) < 0) // case matters; uppercase < lowercase System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”); // will print // will not print // will print // will not print

53 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”); if (s2.compareTo(s1) == 0) System.out.println(“s2 still the same as s1”); if (s2.equals(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”); if (s1 == s2) 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

54 if statements if statement form: –if (boolean expression) java statement; if (x < y) System.out.println(“x < y”); you know both parts now

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

56 Do on board Write an if statement that prints "Before Middle" if String x is alphabetically less than middle and "After Middle" otherwise What’s logically wrong with this?

57 if-else If you want to do one thing if a condition is true and something else if not, use if-else. –form: if (condition) Java statement else Java statement if (x < y) System.out.println(x + " is less than the other number”); else System.out.println(y + " is less than the other number”);

58 > one statement in an if If you want to have more than one statement inside an if or an else, use {}s: if (x < y) { System.out.println(x + " is less than the other number”); x = 0; } else { System.out.println(y + " is less than the other number”); y = 0; }

59 If-else cautions either if clause or else clause or both may have {}s. After statements inside if and else clause are executed, control passes back to next sequential statement no ';' after else Make sure you account for values that are equal

60 Class Work Write an if statement to assign x to y if x is greater than y Consider a class public class MyString { private String s; // write method here } Write the method lessThan that takes a String as a parameter and returns true if s (from MyString) is less than its String parameter

61 Watch Out if (3 < 4) x = 3; else System.out.println(“3 < 4 is false”); x = 0; System.out.println( "the value of x is " + x); Prints what?

62 Embedded ifs 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

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

64 Tracing through the embedded if

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

66 Cautions for embedded ifs Don't use redundant comparisons Make sure you check for values that are equal Account for out of range values

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

68 More complicated embedded ifs if (x < 3) if (y < 6) System.out.println( "x and y between 3 and 6"); else System.out.println( "x = 6"); else if (y > 6) System.out.println( "x and y not in 3-6 range"); else System.out.println( "x >= 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 Spring 2006 Dr. L Lambert. Week 1/2 intro (and Chapter 1)"

Similar presentations


Ads by Google