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

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Mar 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

COMP 110: Introduction to Programming Tyler Johnson Mar 23, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
1 COMP 110 Static Methods and Variables Tabitha Peck M.S. March 24, 2008 MWF 3-3:50 pm Philips 367.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Some basic I/O.
More About Objects and Methods
Numerical Data Recitation – 01/30/2009
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Applications in Java Towson University *Ref:
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
Copyright ©2005  Department of Computer & Information Science Using Number & Math Objects.
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Mt. Rushmore, South Dakota CSE 114 – Computer Science I Static Methods andVariables.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Java Program Components Java Keywords - Java has special keywords that have meaning in Java. - You have already seen a fair amount of keywords. Examples.
Math With Java The Math Class. First, A Quick Review of Math Operators in Java Primitive Data type in Java that represent numbers: Primitive Data type.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
Chapter 2: Java Fundamentals Type conversion,String.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
1 Java Library Lecture 9 by Dr. Norazah Yusof. 2 Java Library Java has pre-defined classes that consist of the basic language classes in Java (organized.
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
COMP 110 Static variables and methods Luv Kohli October 29, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Computing with C# and the.NET Framework Chapter 4 More Control Structures and Types ©2003, 2011 Art Gittleman.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Variables, Types, Operations on Numbers CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Review by Mr. Maasz, Summary of Chapter 2: Starting Out with Java.
Chapter 4 Mathematical Functions, Characters, and Strings 1.
CPSC 233 Tutorial 12 March 4/5 th, TopHat Quiz int[] a = {0}; int[] b = {1}; a = b; What is the value of a[0] i) 0 ii) 1.
More About Objects and Methods
Chapter 4 Mathematical Functions, Characters, and Strings
Chapter 4 Assignment Statement
Static Members and Methods
Chapter 4 Mathematical Functions, Characters, and Strings
More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13.
OUTPUT STATEMENTS GC 201.
Chapter 2.
Static and non-Static Chapter 5.
CMSC 202 Static Methods.
Classes and Objects Miscellany: Statics, Wrappers & Packages
Chapter 4: Mathematical Functions, Characters, and Strings
Chapter 3, cont Sept 20, 2004.
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short.
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Questions? Math Class Wrapper Classes Writing / Testing Methods.
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
Chapter 5 Methods.
CS 200 Primitives and Expressions
Variables, Types, Operations on Numbers
Variables, Types, Operations on Numbers
Building Java Programs
Classes and Objects Static Methods
Using java libraries CGS3416 spring 2019.
Chapter 2: Java Fundamentals cont’d
Variables in C Topics Naming Variables Declaring Variables
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

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

Questions? Constructors Static variables and methods

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; }

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

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

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

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

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

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

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)

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)

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

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

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

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

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

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

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" -> 12.338

Parsing The static methods parseInt & parseDouble can be used as follows double d = Double.parseDouble("199.98"); //d now holds the value 199.98 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

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

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"

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

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!

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}

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();

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(); }

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

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

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!

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

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();

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

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) { … }

Implementation Solve the subtasks to solve the problem

Friday Recitation Bring Laptop (fully charged)