Share

Thursday, July 31, 2008

Getting Keyboard Input for Console Apps: Java's Scanner Class

A nice gift that came with Java 1.5 was the Scanner class. It's part of the java.util package. This class simplifies many common programming tasks. One is getting text from the keyboard.

Prior to Scanner, this took a couple of extra steps. With Scanner, it's a snap. Just as we use System.out to print text to the command line, we use System.in to receive input. Like System.out, System.in is a data stream object. In this case, an InputStream object.

import java.util.Scanner;

public class TrollTalk{
public static void main(String arg[]){
String nayme=""; // Declare & initialize a String to hold input.
Scanner input=new Scanner(System.in); // Decl. & init. a Scanner.

System.out.print("Whut yur nayme? >"); // Troll asks for name.
nayme=input.next(); // Get what the user types.
System.out.println(); // Move down to a fresh line.
// Then say something trollish and use their name.
System.out.println("Hur, hur! Dat's a phunny nayme, " + nayme + "!");
}
}

Our Scanner is named input. We could have called it gzorgnplat, if we wanted to--there's nothing magic about the name 'input'. We attach that name to a new Scanner object that accepts vlues from System.in. Then we print a message so that the user knows they're supposed to type something. The message is a question we want them to answer and a greater-than sign to let them know the computer is ready for them to type.

Being able to accept input while the program is running lets us create interactive command line apps.

Scanner can also be used to get particular types of input like numbers of particular primitive types.

It can also be used to get information from files in the same way it gets information from the user's keyboard. But that's another lesson.
StumbleUpon