more on variables and methods
play

More on variables and methods Robots Learning to Program with Java - PowerPoint PPT Presentation

More on variables and methods Robots Learning to Program with Java Learning to Program with Java Byron Weber Becker chapter 7 h 7 Announcements (Oct 12) Announcements (Oct 12) Reading for Monday g y Ch 7.4-7.5 Program#5


  1. More on variables and methods Robots Learning to Program with Java Learning to Program with Java Byron Weber Becker chapter 7 h 7

  2. Announcements (Oct 12) Announcements (Oct 12) • Reading for Monday g y – Ch 7.4-7.5 • Program#5 out

  3. Character Data Character Data • String is a java class for holding multiple g j g p characters including letters, digits, whitespace, punctuation, etc • Certain characters are given special meaning in C i h i i l i i java and must be handled differently inside strings strings – Double quotes indicate start or end of String data – Single quotes are used to hold a single character – The backslash is used for escape sequences • Inserting a tab • Inserting a line return g • Printing quotes • Printing a backslash

  4. The String class The String class • As with all Java classes instances of type As with all Java classes, instances of type String are objects actually holding a reference to the memory location where reference to the memory location where their instance data is stored • Therefore we should not compare them • Therefore we should not compare them using any of the logical comparison operators : == != < <= > >= operators : ==, !=, <, <=, >, >= • There are several String methods used for comparing String objects i St i bj t

  5. toString toString public String toString() public String toString() • Every well defined Java class has a • Every well defined Java class has a toString method • toString is automatically called by • toString is automatically called by System.out.print or println • toString is also automatically called by • toString is also automatically called by string concatenation • Although there is a concat method you can • Although there is a concat method you can always use + to concatenate strings

  6. Create a Person class that: Create a Person class that: • Holds a String name Holds a String name • Holds 3 integers for the date of birth – month, day, year (always stored as 4 digits) month, day, year (always stored as 4 digits) • Has a constructor that takes only the name • Has a constructor that takes all data Has a constructor that takes all data • Has a setter for birth date that passes 3 ints • Prints the name only • Prints the name only • Prints the name followed by the birthdate (formatted as mm/dd/yyyy – leading zeros not (formatted as mm/dd/yyyy leading zeros not necessary)

  7. Create an Address Class Create an Address Class • Data Data – String street address – String city String city – String state (just 2 letters – always store in uppercase) – String zip code • Constructor takes all data • toString method properly returns the 2 lines of an address label • Getters and setters for all data

  8. Change the Person Class Change the Person Class • Add an Address object to the Person class Add an Address object to the Person class data • Add a constructor that passes the name • Add a constructor that passes the name and Address (as an Address object) • Add a toString method to return an Add t St i th d t t address label • In main, how would you print the city that a , y p y Person lives in?

  9. Student Class Student Class • Subclass of Person • Adds data – Number of points – integer – Number of credit hours - integer Number of credit hours integer – Student ID number – all digits – ULID – ULID password • Adds methods – Getter for ULID password and ID – Getter for ULID, password, and ID – Setter for password – Calculate GPA as points/credit hours – Print an address label P i t dd l b l • toString method for debugging purposes

  10. Static used in a Class for V Variables and Constants i bl d C t t • Static class data (either variable or Static class data (either variable or constant) is created once when the first instance is created and is accessible by all y instances of the class – Thus every instance of a class has the ability to change the value of static variables f • Used very sparingly – If declared as public you can access the value If declared as public you can access the value using the class name double tax = Part.SALES_TAX; _

  11. Static used in a Class for methods Static used in a Class for methods • Static methods cannot be dependent on any Static methods cannot be dependent on any class data that is not also static • Static methods are called using the class name g NOT an instance of the class • The Math class has all static methods and constants – Never create a Math object – Call all methods using Math.methodName() – Access all constants using Math.CONSTANT

  12. Objectives of Ch 7 Objectives of Ch 7 • Write queries to reflect the state of an Write queries to reflect the state of an object • Write a driver method for your class • Write a driver method for your class • Understand various primitive types • Understand the String class • Understand static vs instance variables

  13. Driver method Driver method • Code a little – Test a little Code a little Test a little • A driver method is a main method used simply to test the class methods simply to test the class methods – Can be in a separate class (called the application class) application class) – Can be included in each individual class you write (should be removed when class is write (should be removed when class is finalized) • Extremely useful to programmers to find • Extremely useful to programmers to find logic errors

  14. This code has a logic error This code has a logic error public void setMonthlySalary (int sal) { // allow only non-negative salaries if (this monthlySalary >= 0) if (this.monthlySalary > 0) { this.monthlySalary = sal; } else { System.out.println("Salary must be " + "non-negative!"); } }

  15. Becker’s public class Test http://www.learningwithrobots.com/doc/index.html • Methods to assist in testing code. g – Example usage: public static void main(String[] args) { Patron pat = new Patron(1001); Test.ckEquals("patron ID#", 1001, q ( p , , pat.getID()); } • Each method prints a message on the console indicating whether the test passed or failed and what the expected and actual values were what the expected and actual values were compared.

  16. Primitive Types Primitive Types • Truly hold their data – not references y • Numeric types – byte – short – int – long long – float – double • Other Types – boolean – char

  17. Type Casting Type Casting • Java will not allow you to write code that Java will not allow you to write code that loses precision without explicitly stating that you intend to do so that you intend to do so int intValue; double doubleValue = 5.3; d bl d bl V l 5 3 intValue = doubleValue; //error intValue = (int)doubleValue; • Type casting always truncates – it does Type casting always truncates it does not round

  18. Number Formatters Number Formatters • NumberFormat class – getCurrencyInstance() • Forces value to print with 2 decimal places • Adds a dollar sign to the front • Adds a dollar sign to the front – getPercentInstance() • Adds a percent sign to the end • Converts percentages to integers – Multiplies by 100 so 7 becomes 700% – getNumberInstance() • Allows user to determine the pattern used to print a number – Commas and significant digits are most often used • Note: All returns values are String Note: All returns values are String

  19. Using NumberFormat objects Using NumberFormat objects double value = 2.5; NumberFormat currency = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); NumberFormat number = NumberFormat.getNumberInstance(); System.out.println(currency.format(value)); System.out.println(percent.format(value)); System.out.println(number.format(10000000)); Output… Output… $2.50 250% 10,000,000

  20. Columnar Output Columnar Output • printf method is used to separate printf method is used to separate printed data into columns – This method takes a variable number of This method takes a variable number of arguments • The first argument is the format string which The first argument is the format string which describes how the other arguments should be printed

  21. Format String Specifiers Format String Specifiers • The format string contains a format specifier for each g p column of data • Each format specifier starts with % and is followed by an integer indicating the width of the column integer indicating the width of the column • Positive numbers are used to indicate the data is right justified • Negative numbers are used to indicate the data is left N ti b d t i di t th d t i l ft justified • Each string ends with a letter indicating the kind of data g g in the column – s is used for objects (including String data) using the toString method to determine the output – d is used for integer data – f is used for floating point data (decimals)

Recommend


More recommend