How To Take User Input in Java with Scanner Class
Learn How to take User Input in Java Programming Language. To take Input from the User in Java, you can use either the Scanner class or the BufferedReader class. The Scanner class is a newer and an advanced class with a completely new set of methods than the BufferedReader class. The following guide explains How to Input a String, Integer, Float and Double variables in Java from the User.
Also Read: Java Native Interface Step – By – Step Tutorial with C Programming
About Scanner Class
Scanner is a class available in java.util package. The Scanner class reads formatted input from the user and then converts it into Binary format. The Scanner class is used to read any and every type of value from the user including String, Integers, Floats, Double. The Scanner class is a simple text scanner that parses primitive types and strings using regular expressions.
Scanner Class Declaration
public final class Scanner extends Object implements Iterator<String>
To use the Scanner class in a Java program, you have to import the package in your java program file in the following way. The first import statement includes only the Scanner Class from java.util package. If you want to fetch all the classes from the package, you should use the second method.
Scanner Class needs to be instantiated in order to take Input from the User. The Scanner class can be instantiated in the following way:
Scanner object = new Scanner(System.in);
The system.in() is used to get the Input from the User through the Keyboard. This method needs to be used in the Scanner Object’s Constructor.
Also Read: Java Graphics Program To Draw A Circle
Java Program To Read User Input using Scanner Class
public static void main(String args)
Scanner object1 = new Scanner(System.in);
System.out.println("\nEnter an Integer value: \t");
num1 = object1.nextInt();
System.out.println("\nNumber 1:\t " + num1);
System.out.println("\nEnter a Float value: \t");
num2 = object1.nextFloat();
System.out.println("\nNumber 2:\t " + num2);
System.out.println("\nEnter a Double value: \t");
num3 = object1.nextDouble();
System.out.println("\nNumber 3:\t " + num3);
System.out.println("\nEnter a String: \t");
name1 = object1.next();
System.out.println("\nName 1:\t " + name1);
Also Read: Java Program To Find Public IP Address
If you have any compilation errors or doubts in this Java Program To Take User Input with Scanner Class, let us know about in the Comment Section below.