Regular Expressions 26 The matches Method From the API for the matches method in the String class 27 1
What is the Output? String s1 = "a"; String s2 = "b"; String regex = "a"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "a4"; s2 = "4a"; regex = "[a-z][0-9]"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "abc7"; s2 = "abcd789"; regex = "[a-z]+[0-9]"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "abc123"; s2 = "abcd1234"; regex = "[^0-9]+[0-9]{1,3}"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); See DemoMatches.java 28 Example (count vowels) Write a program that inputs a string from the user. Count and output the number of vowels in the string. DemoRegexVowels.java Instructor Note: Demo from Eclipse 29 2
Example (count punctuation) Write a program that inputs a string from the user. Count and output the number of punctuation characters in the string. DemoRegexPunctuation.java Instructor Note: Demo from Eclipse 30 Example (simple time) Write a program to test whether a string entered by the user represents a time. We're looking only for certain times expressed in a certain way; namely, 3 am, 6 am, 9 am, 3 pm, 6 pm, or 9 pm. DemoRegexTime01.java Instructor Note: Demo from Eclipse 31 3
Example (logical/grouping operators) Write a program to test whether a string represents an integer in the range -25 to +25 DemoRegexIntegerRange.java Instructor Note: Demo from Eclipse 32 Homework (12-hour time) Modify DemoRegexTime01 to handle 12-hour time, according to the following examples: Correct Input 10:00 a.m. 1:59 p.m. 9:12 p.m. 11:59 a.m. 12:00 p.m. 12:00 a.m. Incorrect Input 20:00 a.m. 20:00 p.m. 9:60 p.m. 0:00 a.m. 13:25 pm Solution: DemoRegexTime02.java 33 4
Homework Write a program to test whether a string entered by the user represents a Canadian postal code. Accommodate the possibility of one space or nospace in the middle (i.e., M3J 1P3 and M3J1P3 are both valid postal codes) Solution: DemoRegexPostalCode.java Note: The first letter of a Canadian postal code must be from the set [ABCEGHJKLMNPRSTVXY]. To keep the example simple, accept any other letter in the remaining two letter positions. Accept any digit in the digit positions. 34 Command-Line Arguments By now you have probably noticed that a Java application's main method takes arguments Here's the main method signature: public static main(string[] args) args is a String array; it holds the commandline arguments entered when the app was launched The 1 st argument is args[0], the 2 nd argument is args[1], and so on 35 5
Example Modify CharFreq.java to use command-line arguments. In other words, the string and the character to search for in the string are specified on the command-line, rather through user input after the program launches. Call the program CharFreq02.java. CharFreq02.java Instructor Note: Demo from Eclipse Note: In Eclipse, use Run > Run Configuration > Arguments to specify command-line arguments. Use double quotes around an argument if it includes spaces; e.g., "Test this string" 36 length vs. length() Confusing length and length() is a common programming bug, so length used with arrays; it is an int field holding the length of the array length() used with strings; it is a method that returns an int equal to the length of the string 37 6
The split Method Now that we've discovered String arrays, we can study the split method in the String class split divides a string into a string array based on a regex Characters in the string that match the regex are used to divide the string E.g., String s = "Java is fun"; String[] words = s.split("\\s"); Creates a string array as follows: words[0] "Java" words[1] "is" words[2] "fun" 38 Example (split) Write a program that prompts the user to enter a string of text. Output a count equal to the number of tokens in the string, then output the tokens, one word per line. (Note: A "token" is any sequence of characters separated by one or more whitespace characters.) DemoSplitString.java Instructor Note: Demo from Eclipse 39 7
Example (split) Write a program that opens and reads a text file. Count and print the number of tokens in the file. DemoCountTokens.java Instructor Note: Demo from Eclipse 40 Homework Modify DemoCountTokens to count words A reasonable definition of a word is any sequence of alpha characters (a-z, A-Z) separated by nonalpha characters In order to include contractions (e.g., "don't"), consider the apostrophe an alpha character Print both the count of the number of words and the actual words. Solution: See DemoCountWords.java 41 8
Example Now it's your turn. Write a program to read a text file. Compute some interesting statistics on the contents of the file. Output the results to the console. E.g., What is the longest word? What letter appears most often? What letter appears least often? What word appears most often? (How many times?) etc. 42 Odds and Ends (things not in the text that you need to know) 43 9
Arrays Only mentioned in the text on the subject of command-line arguments and the split method in the String class Arrays are very important in Java (and other computer languages), so Arrays: Useful for storing a collection of information Operations on the collection are performed by iterating through the array Like variables, arrays must be declared and initialized 44 Array Declaration int[] numbers; // int array Brackets indicate that the variable is an array of the indicated type. The size of the array is not yet known or committed. byte[] somebytes; // byte array long[] somelongs; // long array short[] someshorts; // short array double[] realnumbers; // double array float[] morenumbers; // float array char[] somecharacters; // char array boolean[] stateflags; // boolean array Fraction[] somefractions; // object array Of course, object arrays are also possible. 45 10
Array Initialization int[] numbers = new int[6]; numbers[0] = 31; numbers[1] = 25; numbers[2] = -7; numbers[3] = 88; numbers[4] = 99; numbers[5] = 101; An empty int array with six numbers Array initialization Declaration and initialization can be combined. int numbers = { 31, 25, -7, 88, 99, 101 }; 46 Array Access int numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers[0]; Sytstem.out.println(x); Assigns the 0 th element in the numbers array to x int y = numbers[0] % numbers[1]; System.out.println(y); Use array elements in the same way as variables or literals. What is the output? (in-class demo) 47 11
Array Length (length) int[] numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers.length; System.out.printf("Array length = %d\n", x); What is the output? (in-class demo) 48 Array Length vs. Index Array indices go from 0 to length 1 Let's see PrintStream output = System.out; int[] numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers.length; output.printf("array length = %d\n", x); for (int i = 0; i < numbers.length; ++i) output.printf("i = %d, i[%d] = %d\n", i, i, numbers[i]); What is the output? (in-class demo) 49 12
Enhanced For-Loop Iterating through an array: Use a for-loop (as before), or Use an enhanced for-loop for (T variable : collection) { do-something } Works for arrays of objects or arrays of primitive data types See DemoEnhancedForLoop.java 50 Using Arrays Write a program that processes the entries in the numbers array (previous slide). Determine and output (i) the largest number, (ii) the smallest number, and (iii) the mean of the numbers. Solution: DemoUsingArrays01.java 51 13
Thank You 52 14