Presentation is loading. Please wait.

Presentation is loading. Please wait.

Today in COMP 110 Brief static review The Math Class Wrapper Classes

Similar presentations


Presentation on theme: "Today in COMP 110 Brief static review The Math Class Wrapper Classes"— Presentation transcript:

1 Today in COMP 110 Brief static review The Math Class Wrapper Classes
Writing & Testing Methods

2 Questions? Constructors Static variables and methods

3 The Keyword Static The keyword static is used to indicate that only ONE copy of the instance variable or method should exist for the entire class public class UnitsAndMeasures { //static, all objects share the SAME copy of this variable public static final int FEET_PER_YARD = 3; //NOT static, all objects have their OWN copy of this variable private int feet; }

4 Example: Static Instance Variables
A class that counts the number of method calls to ALL of its objects public class StaticExample { //static, all objects share the SAME copy of this variable private static numberOfCalls = 0; public void method() { numberOfCalls++; } public class StaticExampleTester { public static void main(String[] args) { StaticExample se = new StaticExample(); StaticExample se2 = new StaticExample(); se.method(); //changes numberOfCalls to 1 se2.method(); //changes numberOfCalls to 2

5 Accessing Static Variables
From outside the class, static variables that are declared public can be accessed using the name of the class int inchesPerFoot = DimensionConverter.INCHES_PER_FOOT; No Object is Specified! Class Name Static Variable Name

6 Calling Static Methods
From outside the class, static methods that are declared public can be accessed using the name of the class int inches = DimensionConverter.convertFeetToInches(12); No Object is Specified! Class Name Static Method Name

7 The Math Class Provides many standard mathematical methods
All methods are static, no need for an object of the Math class Call methods of the Math class using class name Math.abs Math.max Math.min Math.pow Math.round Others Predefined constants Math.PI Math.E

8 Min/Max, Pow and PI public static double largeToSmallthPower(int a, int b) { double small = Math.min(a, b); //get min of a & b double large = Math.max(a, b); //get max of a & b return Math.pow(large, small); //get large to the smallth power } public static double area(double radius) { return Math.PI * (radius * radius); //use the value of PI in Math class

9 Rounding Math.round can be used to round a floating-point number to the nearest whole number Input: float or double Output: int or long, resp. Examples Math.round(2.3) Returns 2 Math.round(2.7) Returns 3 9

10 Floor Math.floor gives the largest double value that is less than the input and equal to an integer Input: double Output: double Examples Math.floor(2.3) Returns 2.0 Math.floor(2.7)

11 Ceil Math.ceil gives the largest double value that is greater than the input and equal to an integer Input: double Output: double Examples Math.ceil(2.3) Returns 3.0 Math.ceil(2.7)

12 Conversion to int Math.ceil & Math.floor return a double
Math.ceil(5.6) returns 6.0 The result can be type cast int num = (int)Math.ceil(5.6); //type cast result to int 12

13 Review: Primitive Types
Integer types byte, short, int, long Floating-point types float, double Character char Boolean boolean

14 Wrapper Classes Each primitive type has an associated “Wrapper” class
Byte Short Integer Long Float Double Character Boolean

15 Integer Integer is the wrapper class for the type int
//create an object of the Integer class that holds the //integer value 42 in an instance variable Integer n = new Integer(42); int i = n.intValue(); //get the integer value held by the object double d = n.doubleValue(); //convert the integer to a double

16 Double Double is the wrapper class for the type double
//create an object of the Double class that holds the //double value 9.99 in an instance variable Double d = new Double(9.99); double dVal = d.doubleValue(); //get the double value held by //the object

17 Wrapper Classes Wrapper classes have no default constructor
Integer n = new Integer(); //error! - must specify a value Integer n2 = new Integer(24); //ok

18 Parsing The Wrapper classes contain useful methods for “parsing” numbers Parsing means to convert a number from its string representation to a numeric value Example "12.338" ->

19 Parsing The static methods parseInt & parseDouble can be used as follows double d = Double.parseDouble("199.98"); //d now holds the value int i = Integer.parseInt("45"); //i now holds the value 45 String line = keyboard.nextLine(); //get a line of text i = Integer.parseInt(line); //parse to an int

20 Character The Character class defines various useful methods for processing a char Character.toUpperCase Character.toLowerCase Character.isUpperCase Character.isLowerCase Character.isWhiteSpace Character.isLetter Character.isDigit

21 Converting to String Wrapper classes also have a function called toString, which will convert the numeric value held by the object to a string String s = Integer.toString(42); //s now holds the string "42" String s2 = Double.toString(4.2); //s now holds the string "4.2"

22 Writing Methods Solving a problem using decomposition
Divide into subproblems (pseudocode) Solve each subproblem separately Each subproblem becomes a method

23 Decomposition Example
Program 3, find the cheese if isCheeseLeft move left until scent decreases else move right until scent decreases if isCheeseAbove move up until scent decreases move down until scent decreases Bullseye!

24 Decomposition Example
Subproblems isCheeseLeft isCheeseAbove move left,right,up, & down Turn into methods private boolean isCheeseLeft() { … } private boolean isCheeseAbove() { … } private void move(Direction d) { … } enum Direction {LEFT, RIGHT, UP, DOWN}

25 Implementation private boolean isCheeseLeft() {
double powerBefore = mouseBody.sniffForCheese(); mouseBody.moveLeft(); double powerAfter = mouseBody.sniffForCheese(); //move back right to undo our previous move mouseBody.moveRight(); return powerAfter > powerBefore; } private boolean isCheeseAbove() { mouseBody.moveUp(); //move back down to undo our previous move mouseBody.moveDown();

26 Implementation enum Direction {LEFT, RIGHT, UP, DOWN}
private void move(Direction d) { double powerBefore, powerAfter; do { powerBefore = mouseBody.sniffForCheese(); if(d == LEFT) mouseBody.moveLeft(); else if(d == RIGHT) powerAfter = mouseBody.sniffForCheese(); } while(powerAfter > powerBefore); //we moved one too far, move back one mouseBody.moveRight(); }

27 Implementation public void findCheese() { if(isCheeseLeft())
move(LEFT); else move(RIGHT); if(isCheeseAbove()) move(UP); move(DOWN); //BULLSEYE! }

28 Testing Methods A program meant to test a class is called a driver program It is used to “drive” or “exercise” the methods of the class Lab 5 CreditCardAccountTester.java

29 Testing Methods Give the method some simple input
Check that the method has produced the correct result object.setVarA(7); int result = object.getVarA(); if (result==7) System.out.println("get/set VarA Correct"); //if the getter & setter are working correctly, result == 7 Test every method you write in this course!

30 Testing Math.pow double result = Math.pow(2,3); if(result != 8)
System.out.println("Bug in Math.pow"); result = Math.pow(3, 3); if(result != 27)

31 Testing Methods Bottom-Up Testing
Test each method of a class separately If methodA() calls methodB(), test methodB() first //test this first public void methodB() { } //test this second public void methodA() { methodB();

32 Programming Demo Date Validator
The user enters a date in the form "mm/dd/yyyy" Ensure Format, month, day, & year are acceptable

33 Decomposition Divide the problem into subtasks Subtasks become methods
Parse the input into month, day, & year Validate month Validate day Validate year Subtasks become methods private void parseDate(String date) { … } private boolean monthValid(int month) { … } private boolean dayValid(int day) { … } private boolean yearValid(int year) { … }

34 Implementation Solve the subtasks to solve the problem

35 Friday Recitation Bring Laptop (fully charged)


Download ppt "Today in COMP 110 Brief static review The Math Class Wrapper Classes"

Similar presentations


Ads by Google