john hurley spring 2011 cal state la cs 201 lecture 6:

55
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Upload: rosemary-richards

Post on 13-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

John HurleySpring 2011Cal State LA

CS 201 Lecture 6:

Page 2: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Strings

A String consists of zero or more characters

String is a class that contains many methods

Strings are more complicated than they sound!

Page 3: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

3

Constructing StringsString newString = new String(stringLiteral); String message = new String("Welcome to Java");

Since strings are used frequently, Java provides a shorthand initializer for creating a string:

String message = "Welcome to Java";

Page 4: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

4

Strings Are Immutable

A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML";

Page 5: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

5

Trace Code

String s = "Java"; s = "HTML";

: String

String object for "Java"

s

After executing String s = "Java";

After executing s = "HTML";

: String

String object for "Java"

: String

String object for "HTML"

Contents cannot be changed

This string object is now unreferenced

s

animation

Page 6: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

6

Trace Code

String s = "Java"; s = "HTML";

: String

String object for "Java"

s

After executing String s = "Java";

After executing s = "HTML";

: String

String object for "Java"

: String

String object for "HTML"

Contents cannot be changed

This string object is now unreferenced

s

animation

Page 7: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

7

Interned StringsSince strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. For example, the following statements:

Page 8: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

8

Examples

display  s1 == s2 is false s1 == s3 is true

A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.

String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; System.out.println("s1 == s2 is " + (s1 == s2)); System.out.println("s1 == s3 is " + (s1 == s3));

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s1

s2

s3

Page 9: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

9

Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

s1

animation

Page 10: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

10

Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s1

s2

Page 11: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

11

Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s1

s2

s3

Page 12: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

12

String Comparisons java.lang.String

+equals(s1: String): boolean

+equalsIgnoreCase(s1: String): boolean

+compareTo(s1: String): int

+compareToIgnoreCase(s1: String): int

+regionMatches(toffset: int, s1: String, offset: int, len: int): boolean

+regionMatches(ignoreCase: boolean, toffset: int, s1: String, offset: int, len: int): boolean

+startsWith(prefix: String): boolean

+endsWith(suffix: String): boolean

Returns true if this string is equal to string s1.

Returns true if this string is equal to string s1 case-insensitive.

Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.

Same as compareTo except that the comparison is case-insensitive.

Returns true if the specified subregion of this string exactly matches the specified subregion in string s1.

Same as the preceding method except that you can specify whether the match is case-sensitive.

Returns true if this string starts with the specified prefix.

Returns true if this string ends with the specified suffix.

Page 13: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

13

String Comparisonsequals

String s1 = new String("Welcome“);String s2 = "welcome";

if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference }

Page 14: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

14

String Comparisons, cont.compareTo(Object object)

String s1 = new String("Welcome");String s2 = "welcome";

if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2

Page 15: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

public class StringDemo{public static void main(String[] args){

String s1 = new String("Welcome");String s2 = "welcome";String s3 = s1;String s4 = new String("Welcome");

if (s1.equals(s2)){ System.out.println("s1 equals s2");

}else System.out.println("s1 does not equal s2");

if (s1 == s2) {

System.out.println("s1 == s2"); }else System.out.println("s1 != s2");

if (s1.equals(s3)){ System.out.println("s1 equals s3");

}

if (s1 == s3) {System.out.println("s1 == s3");

}else System.out.println("s1 != s3");

if (s1.equals(s4)){ System.out.println("s1 equals s4");

}else System.out.println("s1 does not equal s4");

if (s1 == s4){ System.out.println("s1 == s4");

}else System.out.println("s1 != s4");

if (s1.compareTo(s2) < 0) { System.out.println("s1 < s2");

}

}}

Page 16: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

16

String Length, Characters, and Combining Strings

java.lang.String

+length(): int

+charAt(index: int): char

+concat(s1: String): String

Returns the number of characters in this string.

Returns the character at the specified index from this string.

Returns a new string that concatenate this string with string s1. string.

Page 17: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

17

Finding String LengthFinding string length using the length() method:

message = "Welcome";

message.length() (returns 7)

Page 18: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

18

Retrieving Individual Characters in a String

Do not use message[0]

Use message.charAt(index)

Index starts from 0

W e l c o m e t o J a v a

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message

Indices

message.charAt(0) message.charAt(14) message.length() is 15

Page 19: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

19

String ConcatenationString s3 = s1.concat(s2);

String s3 = s1 + s2;

s1 + s2 + s3 + s4 + s5 same as(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);

Page 20: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Stringspublic static void main(String[] args){

String s1 = new String("Welcome");String s2 = " Shriners";

String s3 = s1.concat(s2);System.out.println(s3);

String s4 = s1 + s2;System.out.println(s4);

s1 = s1 + s2;System.out.println(s1);

if(s1.startsWith("Wel")) System.out.println("\"" + s1 + "\"" + " starts with \"Wel!\"");

System.out.println("Length of \"" + s1 + "\" is " + s1.length());

System.out.println("In the string \"" + s1 + "\", the character at position 4 is " + s1.charAt(4));

}

Page 21: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

21

Extracting Substrings java.lang.String

+subString(beginIndex: int): String

+subString(beginIndex: int, endIndex: int): String

Returns this string’s substring that begins with the character at the specified beginIndex and extends to the end of the string, as shown in Figure 8.6.

Returns this string’s substring that begins at the specified beginIndex and extends to the character at index endIndex – 1, as shown in Figure 8.6. Note that the character at endIndex is not part of the substring.

Page 22: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

22

Extracting SubstringsYou can extract a single character from a string using the charAt method. You can also extract a substring from a string using the substring method in the String class.

String s1 = "Welcome to Java";String s2 = s1.substring(0, 11) + "HTML";

W e l c o m e t o J a v a

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message

Indices

message.substring(0, 11) message.substring(11)

Page 23: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

23

Converting, Replacing, and Splitting Strings

java.lang.String

+toLowerCase(): String

+toUpperCase(): String

+trim(): String

+replace(oldChar: char, newChar: char): String

+replaceFirst(oldString: String, newString: String): String

+replaceAll(oldString: String, newString: String): String

+split(delimiter: String): String[]

Returns a new string with all characters converted to lowercase.

Returns a new string with all characters converted to uppercase.

Returns a new string with blank characters trimmed on both sides.

Returns a new string that replaces all matching character in this string with the new character.

Returns a new string that replaces the first matching substring in this string with the new substring.

Returns a new string that replace all matching substrings in this string with the new substring.

Returns an array of strings consisting of the substrings split by the delimiter.

Page 24: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

24

Examples"Welcome".toLowerCase() returns a new string, welcome."Welcome".toUpperCase() returns a new string, WELCOME." Welcome ".trim() returns a new string, Welcome."Welcome".replace('e', 'A') returns a new string, WAlcomA."Welcome".replaceFirst("e", "AB") returns a new string, WABlcome."Welcome".replace("e", "AB") returns a new string, WABlcomAB."Welcome".replace("el", "AB") returns a new string, WABlcome.

Page 25: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

25

Splitting a String

String[] tokens = "Java#HTML#Perl".split("#", 0);

for (int i = 0; i < tokens.length; i++)

System.out.print(tokens[i] + " ");

Java HTML Perl

displays

Page 26: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

26

Finding a Character or a Substring in a String

java.lang.String

+indexOf(ch: char): int

+indexOf(ch: char, fromIndex: int): int

+indexOf(s: String): int

+indexOf(s: String, fromIndex: int): int

+lastIndexOf(ch: int): int

+lastIndexOf(ch: int,

fromIndex: int): int

+lastIndexOf(s: String): int

+lastIndexOf(s: String,

fromIndex: int): int

Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.

Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1 if not matched.

Returns the index of the first occurrence of string s in this string. Returns -1 if not matched.

Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched.

Returns the index of the last occurrence of ch in the string. Returns -1 if not matched.

Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched.

Returns the index of the last occurrence of string s. Returns -1 if not matched.

Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched.

Page 27: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

27

Finding a Character or a Substring in a String

"Welcome to Java".indexOf('W') returns 0."Welcome to Java".indexOf('x') returns -1."Welcome to Java".indexOf('o', 5) returns 9."Welcome to Java".indexOf("come") returns 3."Welcome to Java".indexOf("Java", 5) returns 11."Welcome to Java".indexOf("java", 5) returns -1."Welcome to Java".lastIndexOf('a') returns 14.

Page 28: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

public class StringDemo5{ public static void main(String[] args){

String theString = "The baby fell out of the window\nI thought that her head would be split\nBut good luck was with us that morning\n" +"For she fell in a bucket of #$%*!\n\nHere we are in this fancy French restaurant\nI hate to be raising a snit\nBut waiter, I ordered cream vichysoisse\nand you " + "brought me a bowl full of #$%*!\n\n";

System.out.println("\nOld:\n" + theString);

String newString = theString.replace("#$%*!", "shaving cream\nBe nice and clean\nShave every day and you'll always look keen!\n");

System.out.println("New:\n" + newString);

}}

Page 29: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

public class StringDemo3{ public static void main(String[] args){ String theString = "'Take some more tea,' the March Hare said to Alice, very earnestly.\n\n'I've had nothing yet,' Alice replied in " +

"an offended tone, 'so I can't take more.'\n\n'You mean you can't take LESS,' said the Hatter: 'it's very easy to take MORE than nothing.'" +

"\n\n'Nobody asked YOUR opinion,' said Alice.";

System.out.println("\n" + theString); System.out.println("\n\nall lower case: " + theString.toLowerCase() + "\n"); System.out.println("\n\nsubstring from index 3 to end: " + theString.substring(3) +

"\n"); System.out.println("\n\nsubstring starting at index 24, ending at 30: "

+theString.substring (24, 30) + "\n"); System.out.println("character at index 39 is: " + theString.charAt(39) + "\n");

System.out.println("\n\nfirst y is at: " + theString.indexOf('y')); System.out.println("\n\nsubstring from first y to last y: " +

theString.substring(theString.indexOf('y'), theString.lastIndexOf('y'))); }

}

Page 30: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

30

StringBuilderThe StringBuilder class is a supplement to

the String class. StringBuilder is more flexible than String. You

can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.

You will often have to parse the StringBuilder to a String when you are done constructing it.

Page 31: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

31

StringBuilder Constructors

java.lang.StringBuilder

+StringBuilder()

+StringBuilder(capacity: int)

+StringBuilder(s: String)

Constructs an empty string builder with capacity 16.

Constructs a string builder with the specified capacity.

Constructs a string builder with the specified string.

Page 32: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

32

Modifying Strings in the Builder

java.lang.StringBuilder

+append(data: char[]): StringBuilder

+append(data: char[], offset: int, len: int): StringBuilder

+append(v: aPrimitiveType): StringBuilder

+append(s: String): StringBuilder

+delete(startIndex: int, endIndex: int): StringBuilder

+deleteCharAt(index: int): StringBuilder

+insert(index: int, data: char[], offset: int, len: int): StringBuilder

+insert(offset: int, data: char[]): StringBuilder

+insert(offset: int, b: aPrimitiveType): StringBuilder

+insert(offset: int, s: String): StringBuilder

+replace(startIndex: int, endIndex: int, s: String): StringBuilder

+reverse(): StringBuilder

+setCharAt(index: int, ch: char): void

Appends a char array into this string builder.

Appends a subarray in data into this string builder.

Appends a primitive type value as a string to this

builder.

Appends a string to this string builder.

Deletes characters from startIndex to endIndex.

Deletes a character at the specified index.

Inserts a subarray of the data in the array to the builder at the specified index.

Inserts data into this builder at the position offset.

Inserts a value converted to a string into this builder.

Inserts a string into this builder at the position offset.

Replaces the characters in this builder from startIndex to endIndex with the specified string.

Reverses the characters in the builder.

Sets a new character at the specified index in this builder.

Page 33: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

33

The toString, capacity, length, setLength, and charAt Methods

java.lang.StringBuilder

+toString(): String

+capacity(): int

+charAt(index: int): char

+length(): int

+setLength(newLength: int): void

+substring(startIndex: int): String

+substring(startIndex: int, endIndex: int): String

+trimToSize(): void

Returns a string object from the string builder.

Returns the capacity of this string builder.

Returns the character at the specified index.

Returns the number of characters in this builder.

Sets a new length in this builder.

Returns a substring starting at startIndex.

Returns a substring from startIndex to endIndex-1.

Reduces the storage size used for the string builder.

Page 34: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

34

ExamplesstringBuilder.append("Java");stringBuilder.insert(11, "HTML and ");stringBuilder.delete(8, 11) changes the builder to Welcome Java.stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java.stringBuilder.reverse() changes the builder to avaJ ot emocleW.stringBuilder.replace(11, 15, "HTML") changes the builder to Welcome to HTML.stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java.

Page 35: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

StringsConsider the chorus of the Irish song “Rare

Old Mountain Dew”:diddly eidel diddle dumdiddly eidel diddle dumdiddly eidel diddly eidel dum day

diddly eidel diddle dumdiddly eidel diddle dumdiddly eidel diddly eidel dum dayThis contains several substrings that are

repeatedHow can we generate this using loops?

Page 36: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Strings and StringBuilderspublic class MountainDew{

public static void main(String[] args){

String diddly = "diddly eidel";

String diddle = "diddle dum";

String dum = "dum day";

StringBuilder sb = new StringBuilder();

for(int counter = 0; counter < 2; counter++){

for(int counter2 = 0; counter2 <= 3; counter2++){

sb.append(diddly + " ");

if(counter2 < 2) {

sb.append(diddle);

sb.append("\n");

}

else if(counter2 == 3) sb.append(dum);

}

if(counter == 0) sb.append("\n\n");

}

System.out.println(sb);

}

}

Page 37: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

StringBuilderpublic class StringBuilderDemo{

public static void main(String[] Args){StringBuilder sb = new StringBuilder("Bakey");System.out.println(sb);

sb.insert(4, "ry");System.out.println(sb);

sb.deleteCharAt(5);System.out.println(sb);

// this will not do what you expect!sb.append(" " + sb.reverse());System.out.println(sb);

sb.delete(sb.indexOf(" "), sb.length());System.out.println(sb);

StringBuilder sb2 = new StringBuilder(sb);sb.deleteCharAt(5);sb2.reverse();sb.append(sb2);

System.out.println(sb);

sb.insert(5," ");System.out.println(sb);

sb.replace(0,0,"Y");System.out.println(sb);

sb.deleteCharAt(1);System.out.println(sb);

sb.reverse();System.out.println(sb);

}}

Page 38: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Dialog Boxes

GUI construction is taught in CS202, but we will cover a few GUI rudiments in 201

The first is the JOptionPane class, which provides pop-up I/O boxes of several kinds

Need to include this at the very top of your class:import javax.swing.JOptionPane;

JOptionPane.showMessageDialog()displays a dialog box with text you specify

Page 39: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Dialog Boxesimport javax.swing.JOptionPane;

public class DialogBox{public static void main(String[] args){

for(int i = 0; i < 4; i++) { JOptionPane.showMessageDialog(null, "This is number " + i);

}}

}

Page 40: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Dialog BoxesJOptionPane.showInputDialog() shows a

dialog box that can take inputThe input is a StringWe will learn soon how to parse from String

to other types

Page 41: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Dialog Boxesimport javax.swing.JOptionPane;

public class InputBox{public static void main(String[] args){

String input = JOptionPane.showInputDialog(null, "Please enter some input ");

JOptionPane.showMessageDialog(null, "You entered: \"" + input + "\"");

String input2 = input.concat(" " + JOptionPane.showInputDialog(null, "Please enter some more input "));

JOptionPane.showMessageDialog(null, "You entered: \"" + input2 + "\"");}

}

Page 42: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Casting Strings to Numeric TypesRecall that input from

JOptionPane.showInputDialog is a String

Cast to integer: Integer.parseInt(intString);Example: String input =

int age = Integer.parseInt(JOptionPane.showInputDialog(null, “Please enter your

age”);Cast to double:

Double.parseDouble(doubleString);

 

Page 43: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Casting to Numeric Types

Note the capitalization in the method names. Double and Integer are not quite the same as double and integer.You’ll understand when you are a little

older…

Page 44: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Parsing to Integerimport javax.swing.JOptionPane;

public class NumericCastDemo{

public static void main(String[] args){

int age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age"));

if(age < 30)

JOptionPane.showMessageDialog(null, age + " is pretty young.");

else if(age > 100) JOptionPane.showMessageDialog(null, "really?");

else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 - age) +

" years older than you are now.");

} // end main()

} // end class

Page 45: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Parsing to Doubleimport javax.swing.JOptionPane;

public class NumericCastDemo{

public static void main(String[] args){

double age = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter your age"));

if(age < 30)

JOptionPane.showMessageDialog(null, age + " is pretty young.");

else if(age > 100) JOptionPane.showMessageDialog(null, "really?");

else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 / age) +

" times as old as you are now.");

} // end main()

} // end class

Page 46: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Imports

We have already discussed javax.swing.JOptionPane methods to show input and message dialogs

These required the following line at the top of the class:Import javax.swing.JOptionPane;

If you omit this line, you will get an error message like this:SwitchDemo.java: 7: cannot find symbolSymbol:variable JOptionPane

Page 47: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Imports

Java classes are organized in packagesLate in this class or early in CS202 you will start using packages for multiple classes

Javax.swing is a package of GUI-related classes that is included with all distributions of Java

JOptionPane is a class within this package

JOptionPane.showMessageDialog() and JOptionPane.showInputDialog are methods of the class

Page 48: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Imports

Including a package in your program adds a small cost, slowing down the compiler as it looks through the imported package

Thus, things like javax.swing are not included automatically; you must specify that you need them

You will eventually be importing your own packages, too.

Don’t leave unused imports in your code

Page 49: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

public class ValueOfDemo{public static void main(String[] args){

double d = 1234.56789;// this would cause an error: int precision=d.indexOf('.');

String stringD = String.valueOf(d);int stringLength = stringD.length();int locationOfDecimalPoint = stringD.indexOf(".");System.out.println("length of string " + stringD + " is " + stringLength + "

location of decimal point is " + locationOfDecimalPoint); int precision = stringLength - locationOfDecimalPoint -1;System.out.println(precision + " digits after the decimal point");

}}

Page 50: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Validating Data TypeWe have already discussed how to make sure that numeric input from Scanner is within a desired range

int age;do {

System.out.println("How old are you?");age = sc.nextInt();

} while (age < 0 || age > 100);

Page 51: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Validating Scanner InputSo far, our programs have crashed if casts to numeric types failed:

Try this with input “two point five”:import java.util.Scanner;public class ReadDouble2 {

public static void main(String[] args) {Scanner input = new Scanner(System.in);Double stuff = 0.0; do {

System.out.print("Input a double. Enter 0 to quit:");

stuff = input.nextDouble();System.out.println("\nYou entered: " +

stuff);} while (stuff != 0.0);

}}

Page 52: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Validating Scanner InputHere is the simplest way to validate Scanner input for data type (that is, to make sure you get input that can be cast to double, integer, etc.)

Scanner has hasNext…() methods that see if there is a parseable tokenhasNextInt()hasNextDouble()hasNextBoolean()

Also need next() to skip over bad input

Page 53: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Validating Scanner InputTry this one with input “nine.three”, then with input “nine point three:

import java.util.Scanner;

public class ReadDouble3 {

public static void main(String[] args) {Scanner input = new Scanner(System.in);Double inpDouble = 10.0;

// bad code ahead!!do {

System.out.print("Input a double. Enter 0 to quit:");if(input.hasNextDouble()){

inpDouble = input.nextDouble();System.out.println("\nYou entered: " + inpDouble);}

else input.next();

} while (inpDouble != 0.0);

}}

Page 54: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Validating Scanner InputIn order to get good output, we need to arrange things in a

slightly more complex way:

import java.util.Scanner;

public class ReadInt{public static void main(String[] args){

Scanner sc = new Scanner(System.in);int x;System.out.println("Enter an integer");while (!sc.hasNextInt()) {

sc.nextLine();System.out.println("No, an integer!");

}x = sc.nextInt();System.out.println(x);

}}

Page 55: John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

55

Convert Character and Numbers to Strings

The String class provides several static valueOf methods for converting characters, arrays of characters, and numeric values to Strings. These methods are named valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.