Scanner is
one of the predefined class which is used for reading the data dynamically from
the keyboard.
Import Scanner class
Syntax
java.util.Scanner
Constructor of Scanner Class
Scanner(InputStream)
This constructor create an object of Scanner class by
talking an object of InputStream class. An object of InputStream class is
called in which is created as a static data member in the
System class.
Example
Scanner sc=new Scanner(System.in);
Here the object 'in' is use the control
of keyboard
Instance methods of Scanner Class
Method
|
Description
|
|
1
|
public byte nextByte()
|
Used for read byte value
|
2
|
public short nextShort()
|
Used for read short value
|
3
|
public int nextInt()
|
Used for read integer value
|
4
|
public long nextLong()
|
Used for read numeric value
|
5
|
public float nextLong()
|
Used for read numeric value
|
6
|
public double nextDouble()
|
Used for read double value
|
7
|
public char nextChar()
|
Used for read character
|
8
|
public boolean nextBoolean()
|
Used for read boolean value
|
9
|
public String nextLine()
|
Used for reading any kind of data in the form of String
data.
|
Method 1 to 8 are used for reading fundamental values
from the keyboard. Method 9 (public String nextLine() ) is used for reading any
kind of data in the form of String data.
For Remember all above methods
From method 1 to 8 combindly we represent as public xxx
nextxxx(). Here xxx represents any fundamental data type. These methods are
used for reading the fundamental data from keyboard.
Accept two values dynamically from the
keyboard and compute sum.
Example
import java.util.Scanner
public class ScannerDemo
{
public static void main(String args[])
{
Scanner s=new
Scanner(System.in);
System.out.println("Enter
first no= ");
int num1=s.nextInt();
System.out.println("Enter
second no= ");
int num2=s.nextInt();
System.out.println("Sum of
no is= "+(num1+num2));
}
}
Output
Enter
first no=4
Enter
second no=5
Sum
of no is=9
Program which is accept two number as a string and compute
their sum.
Example
import java.util.Scanner;
class Dataread
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter
first number: ");
String s1=s.nextLine();
System.out.println("Enter
second number: ");
String s2=s.nextLine();
int res=Integer.parseInt(s1) + Integer.parseInt(s2);
System.out.println("Sum=
"+res);
}
}
Output
Enter
first number: 5
Enter
second number: 6
Sum=
11
I appreciate the assortment of blog posts, I really certainly favored, I like more information around them, considering it is or maybe fabulous., All the finest planned for uncovering.Best 3d scanning Denver, Colorado
ReplyDelete