CSE 21 Intro to Computing II JAVA Objects: String & Scanner 1
Schedule to Semester s End Week of 11/05 - Lecture #8 (11/07), Lab #10 Week of 11/12 - Lecture #9 (11/14), Lab #11, Project #2 Opens Week of 11/19 - Lecture Review (11/21), NO LAB Week of 11/26 - Lecture #11 (11/28), Lab #12 Week of 12/03 - Final Review, Lab #13, Project #2 Due Final Exam: December 12 th from 3:00 to 6:00pm Project #1 Available on Friday November 16 th at 11:55pm Due on Monday December 3 rd at 11:55pm Work alone or in a team of 2 Every student must submit the project Worth 7.5% of your overall grade Understanding Lecture Concepts Code samples: UCMCROPS->Resources->CodeSamples 2
Class String A string is an object containing one or more characters, treated as a unit. Strings are objects. You can think of them as classes that are already available for you to use. The simplest way to create a string is a string literal, which is a series of characters between quotation marks. Example: This is a string literal. You have already used string literals inside print statements. 3
Creating Strings To create a String: First, declare a String object (this is the same way you would declare another data type). Then, assign the String using a string literal or the new operator. Examples: String s1, s2; // Create two String objects s1 = "This is a test."; // Assign to String Literal s2 = new String(); // Create a blank string These steps can be combined on a single line: String s3 = "String 3."; // All together 4
Strings are Very much like arrays! Think of a String as an array of characters Examples: String s1 = Test"; char [] s2 = { C, S, E, 2, 1 }; Accessing characters of the String is done using the charat function (instead of []) Examples: System.out.println(s1.charAt(0) + + s1.charat(1)); System.out.println(s2[0] + + s2[1]); Output: T e C S 5
Strings == arrays of chars! Indices start with 0 Function length()returns the number of chars String astring = new String(); int [] anarray = new int[]; astring.length() // We call a the function length() anarray.length // We get the variable length() Each character is defined by a code (or number) that represents one character The ASCII table defines these codes ASCII stands for American Standard Code for Information Interchange 6
The ASCII table 7
Example of ASCII codes String str = aabcdbcd ; System.out.println(str.charAt(0)); System.out.println((int)str.charAt(0)); for(int i=0; i<str.length(); i++) System.out.print((int)str.charAt(i) +, ); Output a 97 97,65,98,99,100,66,67,68 Note: different codes for upper and lower case! A!= a 8
Comparing String characters We can still use the charat method to get the character Checking if two String are the same String s1 = my string ; String s2 = my string ; if(s1.length()!= s2.length()) System.out.println( NO ); else { for(int i = 0; i < s1.length() ; i++) if( s1.charat(i)!= s2.charat(i)) { System.out.println( NO ); return; } System.out.println( YES );} ASCII codes are used for comparison if (s1.charat(i) == + ) // Checks of character i is + if (s1.charat(i) <= Z && s1.charat(i) >= A ) // If char i is A-Z if (s1.charat(i) <= z && s1.charat(i) >= a ) // If char i is a-z 9
Strings work like other Objects new operator allows us to create objects: String s1 = new String; int [] a = new int[]; We manipulate objects with variables that represent the objects! s1 and a are variable names for a String and an array (of int)! We access functions of objects using the member access (dot) operator sharp.getname(); sharp.setamount(input.nextint()); We can also access String functions using the member access (dot) operator: String s1 = my string ; s1.charat(2); 10
Useful Function: Substring A substring is a portion of a String. The String function substring creates a new String object containing a portion of another String. The function can be called two different ways: s.substring(int startindex); // From <start> to s.length() s.substring(int startindex, int endindex);// <start> to <end> NOTE: IT DOES NOT INCLUDE endindex! This method returns another String object containing the characters from start to end (or the end of the string). 11
Substring Example Examples: String s = "abcdefgh"; String s1 = s.substring(3); String s2 = s.substring(3,6); String s3 = s.substring(1,3); String s4 = s2.substring(1,2); Substring s1 contains "defgh", and substring s2 contains "def". Substring s4 is assigned a substring of s2 Reminder: indices start at 0 s1 s3 s "defgh" "abcdefgh" s.substring(3) s.substring(3,6) bc" s2 "def" s4 "e" 12
Useful Function: Concat The String function concat creates a new String object containing the contents of two strings. The form of this function is: s1.concat(string s2); // Combine s1 and s2 This method returns a String object containing the contents of s1 followed by the contents of s2. 13
Concatenating Strings: Example Example: String s1 = "abc"; String s2 = def ; System.out.println(s1); System.out.println(s2); String s3 = s1.concat(s2); String s4 = s2.concat(s1); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); Output: abc def abc def abcdef defabc 14
Using + for Concatenation Example: String s1 = "abc"; String s2 = def ; System.out.println(s1); System.out.println(s2); String s3 = s1 + s2; // This was s1.concat(s2) String s4 = s2 + s1; // This was s2.concat(s1) System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); Output: abc def abc def abcdef defabc 15
Selected Additional String Methods 16
Scanners Read from User: Scanner kdb = new Scanner (System.in); Pass System.in as parameter to Scanner constructor You can also pass a string as a parameter String example = This is an example ; Scanner line = new Scanner (example); Scanner Functions: next() kdb.next(); line.next(); // get next input word from keyboard // get next input word from string example Scanner Functions: hasnext() line.hasnext() ; check if there is another word in string example Returns a Boolean value (true or false)
Using Scanners to Parse Strings String example = This is an example ; Scanner line= new Scanner (example); while (line.hasnext()) { System.out.println(line.next()); } Note: delimiting character is a space ( ) be default next() function will look for a word until deliminating character is found OUTPUT This is an example
Parsing Strings with Delimiter String example = This,is,an example, with custom,delimiter ; Scanner line = new Scanner (example); line.usedelimiter( [,] ); // Tell scanner to use, as the delimiter while (line.hasnext()) { System.out.println(line.next()); } Delimiting character is comma, NOT a space:, OUTPUT This is an example with custom delimiter
Multiple Delimit Characters String example = + This,is+ an,example ; Scanner input = new Scanner (example); input.usedelimiter( [,+] ); while (input.hasnext()) { System.out.println(input.next()); } Delimiting characters are comma and plus :, + OUTPUT: This is an example
Reading/Processing Files import java.io.*; // Top of your file String filename = nums.txt ; Scanner input = new Scanner (new FileReader(filename)); input.usedelimiter( [\r] ); // use tab and carriage return while (input.hasnext()) { System.out.println(input.next()); } input.close(); This code segment reads a file and outputs its contents line by line Exceptions must be handled when reading files: FileNotFoundException NoSuchElementException
Reading a CSV file import java.io.*; System.out.print("Enter the file name: "); Scanner kdb = new Scanner(System.in); String filename = kdb.next(); try { // TRY it out Scanner input = new Scanner (new FileReader(filename)); while (input.hasnextline()) { Scanner line = new Scanner(input.nextLine()); line.usedelimiter( [,] ); // Tab delimited file while (line.hasnext()){ System.out.print(line.next()); // Read each token System.out.println(); // Done reading one line } } input.close(); } catch (FileNotFoundException e){ // Catch error System.out.println( File could not be found ); } catch (NoSuchElementException e) { // Catch error System.out.println( Tried to use next, with nothing to get ); }
Different Scanner Functions while (input.hasnextline()) { Scanner line = new Scanner(input.nextLine()); line.setdelimiter( [\t\r] ); short s = line.nextshort(); int i = line.nextint(); double d = line.nextdouble(); float f = line.nextfloat(); String str = line.next(); char c = line.next().charat(0); String rest = line.nextline(); } 23
Filenames and Paths String s; s = myfile.txt ; // in current folder s =../myfile.txt ; // previous folder // (relative path) s = C:/tmp/myfile.txt ; // full path specified s = C:\temp-file.txt ; // Error! (\t is a tab!) s = C:\\tmp\\myfile.txt ; // Ok in windows Scanner input = new Scanner (new FileReader(s)); 24