242 210 F II 6 Using Libraries Objectives
242 -210 F II 6. Using Libraries • Objectives – utilize some useful Java libraries • e. g. String, Scanner, Hash. Map, and Random 242 -210 Programming Fundamentals 2 : Libraries/6 Original Slides by Dr. Andrew Davison 1
Topics 1. 2. 3. 4. The String Class The Input. Reader Class Reading Input with Scanner Maps 242 -210 Programming Fundamentals 2 : Libraries/6 2
1. The String Class 242 -210 Programming Fundamentals 2 : Libraries/6 In the java. lang package 3
Creating a String Object 1 String color = "blue"; Four different ways )there are more. ( 2 String s 1 = new String("hello "; ( 3 char chs[] = {‘a’, ‘n’, ‘d’, ‘y’}; String s 2 = new String(chs); 4 String s 3 = s 1 + s 2 + " davison"; + // is string concatenation 242 -210 Programming Fundamentals 2 : Libraries/6 s 1 "hello " 4
Testing Strings for Equality • s 1. equals(s 2( – lexicographical (dictionary) comparison – returns true if s 1 and s 2 contain the same text • s 1 == s 2 – returns true if s 1 and s 2 refer to the same object • Strings should always be compared with equals(). 242 -210 Programming Fundamentals 2 : Libraries/6 continued 5
t 1 • String t 1 = "foo"; String t 2 = "foo"; t 2 "foo" • t 1 == t 2 returns false since t 1 and t 2 are different objects • t 1. equals(t 2) returns true since t 1 and t 2 contain the same text 242 -210 Programming Fundamentals 2 : Libraries/6 6
Comparing Strings • s 1. compare. To(s 2( – returns 0 if s 1 and s 2 are equal – returns < 0 if s 1 > s 2 < ; 0 if s 1 < s 2 • s 1. starts. With("text"( – returns true if s 1 starts with “text” • s 1. ends. With("text"( – returns true if s 1 ends with “text” 242 -210 Programming Fundamentals 2 : Libraries/6 7
Locating Things in Strings for text analysis • s 1. index. Of('c'( – returns index position of first ‘c’ in s 1 , otherwise -1 • s 1. last. Index. Of('c'( – returns index position of last ‘c’ in s 1 , otherwise -1 • Both of these can also take string arguments: – s 1. index. Of("text"( 242 -210 Programming Fundamentals 2 : Libraries/6 8
Extracting Substrings • s 1. substring(5( – returns the substring starting at index position 5 • s 1. substring(1 , 4( – returns substring between positions 1 and 3 – note: second argument is end position + 1 242 -210 Programming Fundamentals 2 : Libraries/6 9
Changing Strings • s 1. replace('a' , 'd'( – return new String object ; replace every ‘a’ by ‘d’ • s 1. to. Lower. Case() – return new String object where every char has been converted to lowercase • s 1. trim() – return new String object where any white space before or after the s 1 text has been removed 242 -210 Programming Fundamentals 2 : Libraries/6 10
How do you Change a String? • Any change to a String object creates a new object, but this can be assigned back to the existing String variable. w String w = "foo"; String new. W = w + "bar"; w = new. W; "foo" or String w = "foo"; w = w + "bar"; 242 -210 Programming Fundamentals 2 : Libraries/6 11
Other String Methods • There are many more String methods! – e. g. s. length() • Look at the Java documentation for the String class. 242 -210 Programming Fundamentals 2 : Libraries/6 12
Strings and Arrays String[] msgs = new String[2]; msgs[0] = "hello"; msgs[1] = new String("hi"); String t = msgs[1]; t. to. Lower. Case(); msgs[1]. to. Lower. Case(); t = msgs[1]. to. Lower. Case(); 242 -210 Programming Fundamentals 2 : Libraries/6 What is built? What is changed? 13
String. Builder • A String. Builder object is like a String, but can be modified – its contents are changed in-place through calls such as append(), without the overhead of creating a new object (as happens with String) • The String. Buffer class is similar to String. Builder but is slower since it can deal with Java threads. String. Builder sb = new String. Builder("Andrew"); sb. append(" Davison"); 242 -210 Programming Fundamentals 2 : Libraries/6 14
The Java API Docs 242 -210 Programming Fundamentals 2 : Libraries/6 15
2. The Input. Reader Class import java. util. *; public class Input. Reader { private Scanner reader; Java's name for stdin / cin public Input. Reader() { reader = new Scanner( System. in ); 242 -210 Programming Fundamentals 2 : Libraries/6 } continued 16
public String get. Input() // Read a line of text from standard input { System. out. print(">> "); // print prompt String input. Line = reader. next. Line(); return input. Line. trim(). to. Lower. Case(); // trim spaces, and make lowercase } // end of get. Input() } // end of Input. Reader class 242 -210 Programming Fundamentals 2 : Libraries/6 17
Combining String Ops String s 1 = " ANDREW s 1 = s 1. trim(); s 1 = s 1. to. Lower. Case(); "; // "ANDREW" // "andrew" • or String s 1 = " ANDREW "; s 1 = s 1. trim(). to. Lower. Case(); 242 -210 Programming Fundamentals 2 : Libraries/6 // "andrew" 18
4. Reading Input with Scanner • The Scanner class reads tokens (words) from an input stream. • The input is broken into tokens based on spaces or regular expressions – the token separator can be changed • The tokens can be Strings, primitive types (e. g. int, float, char, double, boolean), Big. Integers, or Big. Decimals. 242 -210 Programming Fundamentals 2 : Libraries/6 19
Read an Integer from the Keyboard • Scanner sc = new Scanner(System. in); int i = sc. next. Int(); sc. close; () • You specify the input token type by calling methods like next. Int(), next. Double(), etc. 242 -210 Programming Fundamentals 2 : Libraries/6 continued 20
• The next. XXX() method throws an exception (error) when the input doesn't match the expected token type. • next. XXX() ignores spaces before/after the input. 242 -210 Programming Fundamentals 2 : Libraries/6 21
Console. Add. java import java. util. Scanner; public class Console. Add { public static void main(String[] args) { Scanner s = new Scanner( System. in ); System. out. print("Enter first integer: ") int x = s. next. Int(); System. out. print("Enter second integer: ") int y = s. next. Int(); s. close(); System. out. println("Adding gives: " + (x+y) ); } } // end of Console. Add class 242 -210 Programming Fundamentals 2 : Libraries/6 22
Usage 242 -210 Programming Fundamentals 2 : Libraries/6 23
Read floats from a File Scanner sc = new Scanner(new File("floats. txt")); while ( sc. has. Next. Float() ) float f = sc. next. Float(); sc. close; () • Scanner supports many next. XXX() and has. Next. XXX() methods – e. g. next. Boolean() and has. Next. Boolean () • has. Next. XXX() returns true if next. XXX() would succeed. 242 -210 Programming Fundamentals 2 : Libraries/6 24
Floats. Add. java • import java. io. *; import java. util. Scanner; public class Floats. Add { public static void main(String[] args) { float num; float total = 0. 0 f; System. out. println("Openning " + args[0]; ( : 242 -210 Programming Fundamentals 2 : Libraries/6 25
try { Scanner sc = new Scanner( new File(args[0]; ( ( while ( sc. has. Next. Float() ) { num = sc. next. Float(); System. out. println(num); total += num; } sc. close(); } catch(File. Not. Found. Exception e) { System. out. println("Error: " + args[0] + not found"); } " System. out. println("Floats total = " + total ); } } // end of Floats. Add class 242 -210 Programming Fundamentals 2 : Libraries/6 26
floats. txt Input File 242 -210 Programming Fundamentals 2 : Libraries/6 27
Usage 242 -210 Programming Fundamentals 2 : Libraries/6 28
Extract day and year from a String sample. Date = "25 Dec 2007; " Scanner s. Date = Scanner. create(sample. Date; ( int dom = s. Date. next. Int(); String mon = s. Date. next(); int year = s. Date. next. Int(); // gets 25 // gets "Dec" // gets 2007 s. Date. close; () 242 -210 Programming Fundamentals 2 : Libraries/6 29
4. Maps • Maps are collections that contain pairs of objects. – a pair consists of a key and a value • A real-world Map example: – a telephone book name → phone no. • The programmer passes a key to the Map. get() method, and it returns the matching value (or null). 242 -210 Programming Fundamentals 2 : Libraries/6 30
Using a Map • A Hash. Map with Strings as keys and values Hash. Map "Charles Nguyen" "(531) 9392 4587" "Lisa Jones" "(402) 4536 4674" "William H. Smith" "(998) 5488 0123" A telephone book 242 -210 Programming Fundamentals 2 : Libraries/6 31
Coding a Map Hash. Map <String, String> phone. Book = new Hash. Map<String, String>(); phone. Book. put("Charles Nguyen", "(531) 9392 4587"); phone. Book. put("Lisa Jones", "(402) 4536 4674"); phone. Book. put("William H. Smith", "(998) 5488 0123"); String phone. Number = phone. Book. get("Lisa Jones"); System. out. println( phone. Number ); prints: (402) 4536 4674 242 -210 Programming Fundamentals 2 : Libraries/6 32
- Slides: 32