Objectives
- Convert String objects to numeric values
- Convert numeric values to String objects
- Tokenize strings using StringTokenizer
- Tokenize strings using String's "split" method
The following example will catch errors such as the user typing in their name instead of a number.
int value = 0; boolean valid = false; String strIn; java.util.Scanner kbd = new java.util.Scanner(System.in); while (!valid) { System.out.print("Enter an integer: "); strIn = kbd.nextLine(); try { value = Integer.parseInt(strIn); // range checking code could go here valid = true; } catch (NumberFormatException e) { System.out.println("Error: Invalid integer"); } }
String strIn = "This is a test, albeit a short one."; java.util.StringTokenizer tok = new StringTokenizer(strIn, " .,"); System.out.printf("%d tokens were found%n", tok.countTokens()); while (tok.hasMoreTokens()) { String token = tok.nextToken(); System.out.println(token); } // Displays: 8 tokens were found This is a test albeit a short one
String strIn = "Kishwaukee College,CIS 160,A-1374,12"; String[] fields = strIn.split(","); System.out.printf("%d tokens were found%n", fields.length); for (String s : fields) { System.out.println(s); } // Displays: 4 tokens were found Kishwaukee College CIS 160 A-1374 12