The Scanner class is yet another way for Console Input in Java. Here, I will show an example on how to use it.
Attachments:
ScannerDemo.java
First, download the source code above. The lines of codes in this topic are all in that source file. Open it with an IDE or simply Notepad. (For notepad users, click View>Status Bar to see the lines at the bottom. Word Wrap must not be enabled.)
The Scanner class is in the java.util. package. So first, we must include an import statement in our source code heading:
import java.util.Scanner;
Then we of course create an instance of it:
Scanner JInput=new Scanner(System.in);
Take note that JInput is an identifier. It can be anything that you want it to be. For its methods, the Scanner class has basically 10 methods that are commonly used:
next()
nextLine()
nextInt()
nextDouble()
nextFloat()
nextLong()
nextShort()
nextByte()
nextBoolean()
useDelimiter(String)
The methods are used for input just as what primitive date type they present (i.e., nextInt() is used for input of integers, nextBoolean() is for boolean, and nextDouble() is for double value input). The methods next() and nextLine() on the other hand are for String input, though next() only reads and accepts the String after a delimiter character, whilst nextLine() accepts a full String input. The method useDelimiter(String) on the other hand is used to change the delimiter. The String plugged in the parameter will be the new delimiter. To use the above methods, we use our instance(in our sample, JInput) to call the method that we need. Here's an example from the program:
num=JInput.nextInt();
Apparently, the above line asks the user to input an integer value for the variable num. So the other goes out like that and that's all that. Just change the appropriate method for each data type that you wish to input.
Wednesday, June 23, 2010
Scanner Class: A New Approach to Console Input
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment