More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7
Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out
Character Data String is a java class for holding multiple characters including letters, digits, whitespace, punctuation, etc Certain characters are given special meaning in java and must be handled differently inside 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 Printing quotes Printing a backslash
The String class As with all Java classes, instances of type String are objects actually holding a reference to the memory location where their instance data is stored Therefore we should not compare them using any of the logical comparison operators : ==,!=, <, <=, >, >= There are several String methods used for comparing String objects
tostring public String tostring() Every well defined Java class has a tostring method tostring is automatically called by System.out.print or println tostring is also automatically called by string concatenation Although there is a concat method you can always use + to concatenate strings
Create a Person class that: Holds a String name Holds 3 integers for the date of birth 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 setter for birth date that passes 3 ints Prints the name only Prints the name followed by the birthdate (formatted as mm/dd/yyyy leading zeros not necessary)
Data Create an Address Class String street address 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
Change the Person Class Add an Address object to the Person class data Add a constructor that passes the name and Address (as an Address object) Add a tostring method to return an address label In main, how would you print the city that a, y p y Person lives in?
Student Class Subclass of Person Adds data Number of points integer Number of credit hours - integer Student ID number all digits ULID ULID password Adds methods Getter for ULID, password, and ID Setter for password Calculate GPA as points/credit hours Pi Print an address label l tostring method for debugging purposes
Static used in a Class for Variables and Constants t Static class data (either variable or constant) is created once when the first instance is created and is accessible by all instances of the class Thus every instance of a class has the ability to change the value of static variables Used very sparingly If declared as public you can access the value using the class name double tax = Part.SALES_TAX;
Static used in a Class for methods Static methods cannot be dependent on any class data that is not also static Static methods are called using the class name 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
Objectives of Ch 7 Write queries to reflect the state of an object Write a driver method for your class Understand various primitive types Understand the String class Understand static vs instance variables
Driver method Code a little Test a little A driver method is a main method used simply to test the class methods Can be in a separate class (called the application class) Can be included in each individual class you write (should be removed when class is finalized) Extremely useful to programmers to find Extremely useful to programmers to find logic errors
This code has a logic error public void setmonthlysalary (int sal) { } // allow only non-negative salaries if (this.monthlysalary >= 0) { this.monthlysalary = sal; } else { System.out.println("Salary must be " + "non-negative!"); }
Becker s public class Test http://www.learningwithrobots.com/doc/index.html Methods to assist in testing code. Example usage: public static void main(string[] args) { Patron pat = new Patron(1001); Test.ckEquals("patron ID#", 1001, 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 compared.
Primitive Types Truly hold their data not references Numeric types byte short int long float double Other Types boolean char
Type Casting Java will not allow you to write code that loses precision without explicitly stating that you intend to do so int intvalue; double doublevalue l = 5.3; intvalue = doublevalue; //error intvalue = (int)doublevalue; Type casting always truncates it does not round
Number Formatters NumberFormat class getcurrencyinstance() Forces value to print with 2 decimal places 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
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 $2.50 250% 10,000,000
Columnar Output printf method is used to separate printed data into columns 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
Format String Specifiers The format string contains a format specifier for each column of data Each format specifier starts with % and is followed by an 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 justified Each string ends with a letter indicating the kind of data 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)
Formatting Examples NumberFormat money = NumberFormat.getCurrencyInstance(); NumberFormat percentage = NumberFormat.getPercentInstance(); g System.out.println("12345678901234567890"); System.out.printf("%-10s%10d", "string", 5); System.out.println(); System.out.printf("%10s%-10s", "string", money.format(22.5)); System.out.println(); System.out.printf( printf("%10s%10s", "string", percentage.format(.07)); System.out.println();
Formatting output 12345678901234567890 string 5 string$22.50 string 7% "%-10s%10d", %10d" "string", " 5 "%10s%-10s", "string", money.format(22.5) "%10s%10s", "string", percentage.format(.07)
Shortcuts += -= *= /= %= ++ --
Take Care The order of operations can be confusing consider the following int value = 5; value *= 10 + 3; What is held in value after execution? This would convert to value = value * (10 + 3); NOT value = value * 10 + 3;
Character Data String is a java class for holding multiple characters including letters, digits, whitespace, punctuation, etc Certain characters are given special meaning in java and must be handled differently inside 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 Printing quotes Printing a backslash
The String class As with all Java classes, instances of type String are objects actually holding a reference to the memory location where their instance data is stored Therefore we should not compare them using any of the logical comparison operators : ==,!=, <, <=, >, >= There are several String methods used for comparing String objects
Comparing Strings int compareto(string astring) boolean equals(string astring) int comparetoignorecase(string astring) boolean equalsignorecase(string astring)
Extracting Part of a String Sometimes you just want to check on part of a String object or you want to change a single letter of a String object Extracting root words ignoring plurals, etc in a search Change a name to Title Case to ensure all names are stored correctly To do this you must understand how strings are stored and examined character by character
A Brief Intro to Arrays An array is a collection of things or elements In the case of String objects, a String is a collection of typed characters (letters, digits, punctuation marks, white space, and other special characters) Each element in an array is given an index that indicates its placement in the array Indices start at zero! The index is used to access the element This takes place inside the String class. Therefore it is not necessary that t you understand d it at this point. It will be covered in detail later Strings are stored as arrays of characters and can be manipulated element by element
Some Useful String Methods char charat(int index) returns the single character at a particular index char letter = mystring.charat(0); returns a copy of the first letter in the String int indexof(char ch) returns the index of a given character IF it occurs in the String. If the character does not occur, -1 is returned int indexof(char ch, int fromindex) searches for the given character starting from a particular index int indexof(string substring) returns the starting index of a given substring within the String int length() returns the number of characters in a string this is a very useful method
Changing Case String touppercase() returns a new String in all uppercase String tolowercase() returns a new String in all lowercase Note these methods do not change the original String object!
MoreOnTheStringClass The String constructor is not necessary String name = Bob Smith ; String name = new String( Jill Smith ); String concatenation take care System.out.println(1 + 5 + " is 6"); System.out.println("1 + 5 is " + 1 + 5);
substring public String substring(int index) Returns a portion of the calling string starting at the index and going g to the end of the string public String substring(int start, int end) Returns a portion of the calling string starting at the start index and stopping in front of the end index
More About the String Class Methods in the String class (and most Java classes) are very well named You need to know the character at a particular index charat You need to know the index of a specific character in a String indexof You want to change the case of an entire String touppercase or tolowercase You want to pull part of a String out into a new String substring Use the API to help you find methods Read the short description, but also look at the longer description http://java.sun.com/javase/6/docs/api/