Java Input with Scanner

This article will explain how to take input from the user using the Java Scanner class.

There are ways than one to take input from the user in Java, and the Scanner class is only of them. However, it is probably the most commonly used as well due it’s ease of use. Another common way is the System.in.read() function, which does not require the use of any additional class or library. It can be a little difficult to manage at times though.


Taking input with Scanner

The first thing to do is to import the Scanner Class into your java program. This allows you to use the methods belonging to the Scanner Class.

import java.util.Scanner;

Next step is to create an object of the Scanner class. If you’ve know Java Classes, you’ll know how to create class objects.

Scanner input = new Scanner(System.in);

Finally we take input using the following command.

int number = input.nextInt();

Notice that we use the nextInt() function here. This only allows for the user the enter integers as input. The Java scanner class has different methods for different input data types. See the table below to see all of them.

MethodsDescription
nextInt() Accepts Integer values from the user
nextLong() Accepts Long values from the user
nextShort() Accepts Short values from the user
nextFloat() Accepts Float values from the user
nextDouble() Accepts Double values from the user
nextLine()Accepts a line from the user
next() Accepts a single word from the user
nextByte() Accepts Byte values from the user
nextBoolean() Accepts Boolean values from the user

Entering data of the incorrect data type will result in the InputMismatchException as shown below.


Examples

Below is a full example of the use of the Java Scanner in taking input. Note the use of the close() function. This is a part of memory management in Java. It’s not a compulsory step, but it’s good practice to do so.

import java.util.Scanner;

public class example {
	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		
		System.out.print("Input a number: ");
		int number = input.nextInt();
		System.out.println(number);
		
		System.out.print("Input a Boolean value: ");
		boolean YesNo = input.nextBoolean();
		System.out.println(YesNo);
		
		System.out.print("Input a Decimal: ");
		float Decimals = input.nextFloat();
		System.out.println(Decimals);
	
		System.out.print("Input a String: ");
		String text = input.next();
		System.out.println(text);	
		
		input.close();
	}
}
Input a number: 2020
2020
Input a Boolean value: false
false
Input a Decimal: 4.87
4.87
Input a String: Hello 
Hello

This marks the end of the Java Scanner input article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments