1 / 30

Writing methods and Java Statements

Writing methods and Java Statements. Java program. import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables or fields // constructors. with no parameters is Default // methods }. Methods.

roya
Download Presentation

Writing methods and Java Statements

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. Writing methods and Java Statements

  2. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables or fields // constructors. with no parameters is Default // methods }

  3. Methods public/private returntype name ( /* parameter list */ ) { // statements } public void myMethod( ) { // empty body }

  4. Writing our own method: calcVolume public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; // or george. call it anything volume = 4 / 3 * PI * radius * radius * radius; return volume; }

  5. return type double first line signature or header (visible in external view also) Local variable and constant stuff inside curly braces is method body Java statements inside body, e.g., single = assignment return statement Class Details: Methods public double calcVolume( ) { // NO private in local variables; final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; }

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

  7. instance variable (field) vs. Local variable • local variables declare in a method; instance variables outside of all methods • local variables have the lifetime of the method call • local variables and instance variables have type and ‘;’ • local variables do NOT have private/public designation • when possible, use local variables

  8. Writing methods: Java statementsmust be within a method • Arithmetic Expressions • Compound Assignment • System.out.println • new • dot notation: external method calls • return • JOptionPane

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

  10. 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; • single increment • ++count OR count++; // does the same as count += 1 • --count OR count--; // does the same as count -=1

  11. Math Problems • int x=3; double y=4.0; x + y // this is ok even though different types x / 2 y / 3 x % 2 x % 3 x++ x += 5 x = y; // ok, but truncated x *= 2 // ++, --, +=, etc. work for doubles also

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

  13. 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);

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

  15. 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

  16. Most important slide of CS150: Objects, new, dot • To declare an object: • NameOfType variableName; • To create the object, call its constructor with new • variableName = new NameOfType( ); /* often, caps is class & constructor, lowercase is variable/object. 2 different things. caps is type of dog, lowercase, actual dog */ • name = new Name( ); • To do something with the object, use variableName dot methodname • variableName.DoSomething( );

  17. New practice on board • Declare a variable george of type Picture. Call its constructor. • Call george's draw method (use dot notation. to call a method within a class, no dots).

  18. Practice Assume that there is a Fraction class that has a write method which prints the Fraction, and two constructors, one that creates some default Fraction value and one that allows two parameters to be passed (e.g., Fraction(3, 4) would create the fraction 3/4). Write a UseFraction class that has two instance variables, both Fractions. Make one the default value and other 4/7. Print both of them out.

  19. CNU campus • Write two classes, one a Building class and one a Campus class. • Buildings have names, number of floors, square feet. Write getName, getFloors, getFeet methods. • Campuses have 3 buildings and a name, a print method that prints school name and building info • Write a Building class; write a Campus class; • Create a campus class. Call its print method

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

  21. return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation

  22. Other most important slide:Understanding method calls, object creation public class TestVolume // note: NO ( )s for class { public static void main(String[ ] args) { Sphere sphere = new Sphere( ); double george; george = sphere.calcVolume( ); System.out.println("value is " + george); }

  23. Trace • on board • using debugger

  24. return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation What is the fix?

  25. Casting • Lesson 1: always test every method • Lesson 2: don’t assume answer is correct; check it • Fix 1: double volume = 4 / 3; • Lesson 3: int / int REALLY is int. • Fix 2: volume = (double) 4/3 * PI * radius * radius * radius; • Casting should be used when you know the type of the result. int to double ok. double to int, not ok

  26. JOptionPane, Section 1.11 • To display a message: import javax.swing.JOptionPane; JOptionPane.showMessageDialog( null, // for now, always null "message: I LOVE cpsc150!!!", "Window Title", JOptionPane.INFORMATION_MESSAGE);

  27. Reading information inJOptionPane, Section 2.11 String answer = JOptionPane.showInputDialog(null, "What is the weather today", "Weather Predictor", JOptionPane.QUESTION_MESSAGE); System.out.println("The weather is " + answer);

  28. Reading information,Section 2.11converting strings to ints String answer = JOptionPane.showInputDialog(null, "Enter a number", "Window Title", JOptionPane.QUESTION_MESSAGE); System.out.println("Answer is " + answer); // answer*1 error int number = Integer.parseInt(answer); // turns Strings to nbrs System.out.println("Answer is " + number*1);

  29. Source Code Review Terms • import • comments // and /* … */ and /** javadoc here */ • public/private • can't see draw; can see changeColor • class • class name • case sensitive. convention, start with capital • fields/instance variables • always private, outside everything except class • specify data type (can be primitive or object) and name • primitive data types: int, double, boolean, char, a few others • lowercase • can be initialized; all other statements must be within a method • constructor • can have more than one. each must have different signature • always the name of the class. never has a return value

  30. Review • method (definition) • Java statements • return type (void if nothing returned) • parameters • local variable • assignment • +, -, *, /, % (result is same as operands) • =, ++, --, +=, -=, *=, /= • System.out.println • method call • new • dot notation • JOptionPane for reading and writing

More Related