-
The Scanner
class has two methods for reading textual input from the keyboard.
-
The next
method returns a reference to a String
object that has from zero to many characters typed by the user at the keyboard. The String
will end whenever it reaches white space. White space is defined as blank spaces, tabs, or newline characters in the input stream. When inputting from the keyboard, next
stops adding text to the String
object when the first white space is encountered from the input stream.
-
A nextLine
method returns a reference to a String
object that contains from zero to many characters entered by the user. With nextLine
, the String
object may contain blank spaces and tabs but will end when it reaches a newline character. Therefore, nextLine
will read in whole lines of input rather than only one word at a time.
- String input is illustrated below.
Scanner keyboard = new Scanner(System.in);
String word1, word2, anotherLine;
// prompt for input from the keyboard
System.out.print("Enter a line: ");
// grab the first "word"
word1 = keyboard.next();
// grab the second "word"
word2 = keyboard.next();
// prompt for input from the keyboard
System.out.print("Enter another line: ");
// discard any remaining input from previous line
// and read the next line of input
anotherLine = keyboard.nextLine(); //skip to the next line
anotherLine = keyboard.nextLine(); //grab all of the next line
// output the strings
System.out.println("word1 = " + word1);
System.out.println("word2 = " + word2);
System.out.println("anotherLine = " + anotherLine);
Run Output:
Enter a line: Hello World! This will be discarded.
Enter another line: This line includes whitespace.
word1 = Hello
word2 = World!
anotherLine = This line includes whitespace.
- Formatting Strings is done with the same style as using the
printf()
method discussed in Lesson A7, Simple I/O. In fact, now that you know more about Strings, you should be able to recognize that you are really manipulating String literals when you use the printf()
formatting rules. If you want to alter how a String object is stored without actually printing it to the String, you can simply use a Formatter object (which is actually the object that printf()
uses itself). An example of how to use Formatter is shown below. Note: Don’t forget to import the Formatter class.
import java.util.Formatter;
Formatter f = new Formatter();
f.format("%10s","Bob");
String bob = f.toString();
System.out.println(bob.length());
System.out.println(bob);
Run Output:
10
Bob