Java_6_Scanner Class
Java_6_Scanner Class
Syntax:
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation.
Ex1: In our example, we will use the nextLine() method, which is used to read Strings:
Input Types:
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
Method Description
import java.util.Scanner;
class demo {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input (Integer and double value)
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
//System.out.println(name + " is of type " + ((Object)name).getClass().getSimpleName());
//System.out.println(age + " is of type " + ((Object)age).getClass().getSimpleName());
//System.out.println(salary+ " is of type " +((Object)salary).getClass().getSimpleName());
}
}
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error
message (like "InputMismatchException").
The following example allows user to read an integer form the System.in.
1. import java.util.*;
2. class UserInputDemo
3. {
4. public static void main(String[] args)
5. {
6. Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7. System.out.print("Enter first number- ");
8. int a= sc.nextInt();
9. System.out.print("Enter second number- ");
10. int b= sc.nextInt();
11. System.out.print("Enter third number- ");
12. int c= sc.nextInt();
13. int d=a+b+c;
14. System.out.println("Total= " +d);
15. }
16. }
Example of String Input from user
1. import java.util.*;
2. class UserInputDemo1
3. {
4. public static void main(String[] args)
5. {
6. Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7. System.out.print("Enter a string: ");
8. String str= sc.nextLine(); //reads string
9. System.out.print("You have entered: "+str);
10. }
11. }
Note: