1 / 63

CPSC150

CPSC150. Fall 2005 Dr. L Lambert. Week 1. Chapter 1 Java, BlueJ, Objects, Terms. 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

Download Presentation

CPSC150

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  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. Dr. L. Lambert

  4. 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). • 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) • 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. Dr. L. Lambert

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

  6. 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++) Dr. L. Lambert

  7. 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 Dr. L. Lambert

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

  9. Looking at an Example:External View • 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 . (dot MUST be there) Dr. L. Lambert

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

  11. Quiz: week 2(= you know enough to do Quiz 1) • 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. • 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 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 <= 300 and y >= 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. Dr. L. Lambert

  12. Review • External View • In BlueJ main window, • Classes • Object bench • Class relationships • Create Objects • Call/Invoke Methods of objects Dr. L. Lambert

  13. Source Code (Internal View) • import • Comments // single line /* */ multiline /** */ Javadoc • Class definitions public class Picture { // fields // constructors // methods } Dr. L. Lambert

  14. 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; • user and library defined • BlueJ: primitive has data; object has pointer • Clock example, ClockDisplay, NumberDisplay (Inspect object in /home/lambert/Public/projects/chapter03/clock-display) Dr. L. Lambert

  15. Source Code (Internal View) • import • Comments // single line /* */ multiline /** */ Javadoc • Class definitions public class Picture { // fields // constructors // methods } Dr. L. Lambert

  16. Class details: constructors • Initialize objects. Called when object is created • no return type • can be overloaded public Circle( ) { // 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 diameter = d; xPosition = x; yPosition = y; color = c; isVisible = false; } Dr. L. Lambert

  17. Work on Quiz Time • 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. • 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 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 <= 300 and y >= 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 theif. Dr. L. Lambert

  18. 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 Dr. L. Lambert

  19. first line signature or header (visible in external view also) return type void formal parameter curly braces, stuff inside is method body Java statements inside body, e.g., single = assignment Class Details: Methods • General Structure: public/private return-type name (param1name param1type, param2name param2type) • changeColor method from Circle: public void changeColor(String newColor) { color = newColor; draw( ); } Method call (with actual parameters if necessary) Internal method call Dr. L. Lambert

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

  21. 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 Dr. L. Lambert

  22. Writing methods:More Java statements • Arithmetic Expressions • Compound Assignment • System.out.println • this • new • dot notation: external method calls • return Dr. L. Lambert

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

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

  25. Math ProblemsDo on board • int x=3; double y=4.0; x+y x/2 y/3 x%2 x%3 Dr. L. Lambert

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

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

  28. 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 Dr. L. Lambert

  29. Quiz Work • 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. • 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 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 <= 300 and y >= 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 theif. Dr. L. Lambert

  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 Dr. L. Lambert

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

  32. Common methods: Accessor • Retrieve the value of a field • no parameter, return type is type of field • method body is one line public class Fraction { // only a little bit defined private int numerator; private int denominator; public int getNum() { return numerator; } } Dr. L. Lambert

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

  34. Work on Quiz 2 • 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. • 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 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 <= 300 and y >= 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 theif. Dr. L. Lambert

  35. 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. • Change print to call toString • 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 Dr. L. Lambert

  36. Quiz: Week 3 • 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. • 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). • 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. Dr. L. Lambert

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

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

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

  40. Relational Operatorsfor 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) Dr. L. Lambert

  41. Evaluating Boolean ExpressionsDo on board with partners int x=3; int y = 4; int z=5; x < y true x < y < z error: < cannot be applied to boolean,int x = y error: incompatible types - found int; expected boolean y == 4 true z >= x false x != 3 false (x + 4) < (y - 1) 7 < 3; false Dr. L. Lambert

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

  43. 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) Logical OperatorsDo on board Dr. L. Lambert

  44. 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 More logical operatorsDo on board Dr. L. Lambert

  45. 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 Yet more logical operatorsDo on board Dr. L. Lambert

  46. 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 Dr. L. Lambert

  47. CompareTo • Returns 0 if 2 Strings are equal • Returns negative number if object<parameter • Returns positive number if object > parameter Dr. L. Lambert

  48. compareTo codewrite 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 Dr. L. Lambert

  49. More String comparisionson 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 print // will print; symmetric // compareTo == 0 is same as equals // will print // will not print // will not print Dr. L. Lambert

  50. if statements • if statement form: • if (boolean expression) java statement; if (x < y) System.out.println(“x < y”); you know both parts now Dr. L. Lambert

More Related