Java Scanner Class – How to import it and use it in Java

By | April 6, 2018

Java-Scanner-Class

Scanner is a class which is present in java.util package. It is used for receiving input from user. It takes the input from user into tokens. We convert those tokens into required types using nextXYZ() methods. (Here XYZ can be int, long etc).

How to take input from user in Java using Scanner class?

Here is the sample program to take input from User using Scanner class in java

 

 import java.util.Scanner; 
class ScannerTest
{
	 
	public static void main(String[] args) 
	{
		String name=""; 
		System.out.println("Enter your Name");
		Scanner buff = new Scanner(System.in); 
		name=buff.nextLine();

		System.out.println("Hello "+name);
	}
}

 

Explanation of above Scanner Class Program in Java

Line 1:- Here we are importing Scanner class

Line 2:- ScannerTest is the name of the class

Line 5:- This is the main method

Line 7:- String variable name with a default value. Why default value? It is compulsory to initialize local variables in java.

Line 9:- Here we are creating Scanner class Object and passing pre-defined object system.in in its constructor.

Line 10:- Using nextLine() method to take input from user as a String

Line 11:- Printing the name of the user.

 

Some common doubts about Scanner class in java

What is System.in in Scanner class in Java?

Ans:- System is class present in java.lang package. In that class, there is a static variable of the type InputStream whose name is in. So basically it is an object of the type InputStream which is present in System class. We pass that object in the constructor of Scanner class.

 

Some frequently used methods in Scanner class

nextInt() – To read integer value

nextLong() – To read long value

nextDouble() – To read double value

next() – It will read String value before getting any space. You cannot use this method to receive a String with space.

nextLine() – It will read String value with space.

hasNext() – It will return boolean value true if Scanner object has another token.

hasNextInt() – It will return boolean value true if Scanner object has Integer value token.

 

Another program using Scanner class in java

 

 import java.util.Scanner; 
class ScannerTest
{
	 
	public static void main(String[] args) 
	{
		int sum = 0;
		System.out.println("Enter values to get Sum ");
		Scanner buff = new Scanner(System.in);
		while (buff.hasNextInt()==true)
		{
			sum = sum+buff.nextInt();
		}
		System.out.println("Sum is "+sum);
	}
}

Explanation of above Java Scanner Class Example Program

Above program will take values from the user until it encounters any value other than Integer.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.