Read Input From User in Java.

Java User Input

In Java, Input can be read from the keyboard in many ways. One such way is to use the predefined/inbuilt class Scanner which is present in java.util package. Predefined/inbuilt classes in Java are organized in the form of packages. To use Scanner class, include package java.util using import statement as:

//import just a Scanner class
import java.util.Scanner;

//import the entire package java.util
import java.util.*;

Next, create a Scanner object to give input from the system from the given keyboard.

  • Scanner sc = new Scanner(System.in);
import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter Roll No: ");
		int rollNo = sc.nextInt(); //integer input
		
		System.out.println("Enter Student name: ");
		String name = sc.next();  //single word input
		
		System.out.println(rollNo+" : "+name);
	}
}
Output:
Enter Roll No:
112
Enter Student name:
John
112 : John

Like in the above example, the Scanner class has methods to get input of various data types. 

Methods Data Type
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Short
nextBoolean() Boolean
next() Single word (String without space)
nextLine() String without space
* For next() :even if you try to input multiple words, the will takes the first word only as input


Important note: Reading String using nextLine().

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Student name: ");
String name = sc.next();

System.out.println("Enter the Address: ");
String address = sc.nextLine();

System.out.println("Name: "+name+" Address: "+address);

When you will execute the above code, the address will not be taken as input because Scanner skips the nextLine() when it is used after the next() or nextXxx() (ex: nextInt()) method. It is because the next() reads only the String, not the new line, and nextLine() consumes the next line (\n) as input, hence no input is received. 

To overcome this problem, when using nextLine() after next() or nextXxx(), consume the new line by including the statement sc.nextLine(). See the below example to understand more. 

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter Roll No: ");
		int rollNo = sc.nextInt();
		
		//captures the new line 
		sc.nextLine(); 
		System.out.println("Enter Student Full Name: ");
		String name = sc.nextLine();
		
		System.out.println(rollNo+" : "+name);
	}
}
Output:
Enter Roll No: 
112
Enter Student Full Name: 
John Gupta
112 : John Gupta

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS