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 - - 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
Announcements (Oct 12) Announcements (Oct 12)
- Reading for Monday
g y – Ch 7.4-7.5
- Program#5 out
Character Data Character Data
- String is a java class for holding multiple
g j g p characters including letters, digits, whitespace, punctuation, etc C i h i i l i i
- Certain characters are given special meaning in
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
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
- perators : == != < <= > >=
- perators : ==, !=, <, <=, >, >=
- There are several String methods used for
i St i bj t comparing String objects
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
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)
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
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 t St i th d t t
- 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 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 P i t dd l b l – Print an address label
- toString method for debugging purposes
Static used in a Class for V i bl d C t t Variables and Constants
- 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 f to change the value of static variables
- 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; _
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
Objectives of Ch 7 Objectives of Ch 7
- Write queries to reflect the state of an
Write queries to reflect the state of an
- bject
- 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
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
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!"); } }
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.
Primitive Types Primitive Types
- Truly hold their data – not references
y
- Numeric types
– byte – short – int long – long – float – double
- Other Types
– boolean – char
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; d bl d bl V l 5 3 double doubleValue = 5.3; intValue = doubleValue; //error intValue = (int)doubleValue;
- Type casting always truncates – it does
Type casting always truncates it does not round
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
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
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
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 N ti b d t i di t th d t i l ft
- Negative numbers are used to indicate the data is left
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)
Formatting Examples Formatting Examples
NumberFormat money = NumberFormat getCurrencyInstance(); 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)); money.format(22.5)); System.out.println(); System out printf("%10s%10s" "string" System.out.printf( %10s%10s , string , percentage.format(.07)); System.out.println();
Formatting output Formatting output
12345678901234567890 t i 5
"% 10 %10d" " t i " 5
string 5 string$22.50
"%-10s%10d", "string", 5 "%10s%-10s", "string", money.format(22.5)
string 7%
"%10s%10s", "string", percentage.format(.07)
Shortcuts Shortcuts
- +=
+=
- -=
*
- *=
- /=
- %=
- ++
++
- --
Take Care Take Care
- The order of operations can be confusing
The order of operations can be confusing – consider the following int value = 5; int value 5; value *= 10 + 3;
- What is held in value after execution?
- What is held in value after execution?
- This would convert to
l l * (10 + 3) value = value * (10 + 3); NOT value = value * 10 + 3;
Character Data Character Data
- String is a java class for holding multiple
g j g p characters including letters, digits, whitespace, punctuation, etc C i h i i l i i
- Certain characters are given special meaning in
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
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
- perators : == != < <= > >=
- perators : ==, !=, <, <=, >, >=
- There are several String methods used for
i St i bj t comparing String objects
Comparing Strings Comparing Strings
- int compareTo(String aString)
int compareTo(String aString)
- boolean equals(String aString)
- int compareToIgnoreCase(String
aString) aString)
- boolean equalsIgnoreCase(String
aString) g)
Extracting Part of a String Extracting Part of a String
- Sometimes you just want to check on part
Sometimes you just want to check on part
- f a String object – or you want to change
a single letter of a String object a single letter of a String object
– Extracting root words – ignoring plurals, etc in a search a search – Change a name to Title Case to ensure all names are stored correctly names are stored correctly
- To do this you must understand how
strings are stored and examined character strings are stored and examined character by character
A Brief Intro to Arrays A Brief Intro to Arrays
- An array is a collection of “things” or elements
y g
- In the case of String objects, a String is a collection of
typed characters (letters, digits, punctuation marks, white space, and other special characters) 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! – Indices start at zero!
- The index is used to access the element
– This takes place inside the String class. Therefore it is not th t d t d it t thi i t It ill b d necessary that you understand it at this point. It will be covered in detail later
- Strings are stored as arrays of characters and can be
i l t d l t b l t manipulated element by element
Some Useful String Methods 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 py g
- 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 not occur, 1 is returned
- int indexOf(char ch, int fromIndex) –
searches for the given character starting from a particular index 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 Changing Case
- String toUpperCase() – returns a
String toUpperCase() returns a new String in all uppercase
- String toLowerCase()
returns a
- String toLowerCase() – returns a
new String in all lowercase N t th th d d t h th
- Note these methods do not change the
- riginal String object!
More On The String Class More On The String Class
- The String constructor is not necessary
The String constructor is not necessary
String name = “Bob Smith”; String name = new String(“Jill Smith”); g g( );
- String concatenation – take care…
String concatenation take care…
System.out.println(1 + 5 + " is 6"); System.out.println("1 + 5 is " + 1 + 5);
substring substring
public String substring(int index)
- Returns a portion of the calling string
starting at the index and going to the end g g g
- f the string
public String substring(int start, int end)
- Returns a portion of the calling string
starting at the start index and stopping in g pp g front of the end index
More About the String Class More About the String Class
- Methods in the String class (and most Java
g ( 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 – 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 subs g
- Use the API to help you find methods
- Read the short description, but also look at the