Java Scanner Class
üScanner class is used to read input from the
keyboard, a file, a
string or any source that implements the Readable or
ReadByteChannel.
üScanner can be created for a
string, an InputStream, or any
object that implements Readable or ReadByteChannel interface.
üScanner class is under the package
of java.util
üAdded in J2SE 5.
Readable Interface:
üIt is added by J2SE.
üIt is included in Java.lang.
üIt defines one method:
int read(CharBuffer buf) throws IOException
Taking Input from the Keyboard
üFirst, Scanner class is connected
to System.in which is an object of type InputStream.
üThen, it uses it’s internal functions to read from
System.in
Example:
Scanner
test = new Scanner(System.in);
Take
an input from the keyboard-1
import
java.util.*;
public
static void main(String[] args) {
int value;
System.out.print(“Enter an Integer number:");
Scanner tmp =
new Scanner(System.in);
if(tmp.hasNextInt())
{
value=tmp.nextInt();
System.out.println(“You have entered: ”+value);
}
else
System.out.println(“Not an Integer”);
}
Taking
Input from the KeyBoard-2
import
java.util.*;
class
input
{
public static void main(String args[])
{
Scanner tmp = new Scanner(System.in);
float i;
while(tmp.hasNextFloat())
{
i=tmp.nextFloat();
System.out.println("The Number: ",i);
}
}
}
No comments:
Post a Comment