In java we can take input by using Scanner class and InputStreamReader class.
Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.
To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example:
Scanner in = new Scanner(System.in);
inside Scanner class there many types of Methods/functions are there:
next() : used to accept sting value (only one word).
nextLine():used to accept sting value (whole sentence).
nextInt(): used to accept int type values.
nextLong(): used to accept long type values.
nextDouble():used to accept double type values.
nextFloat():used to accept float type values.
nextByte():used to accept byte type values.
etc.
Let's see a simple example of Java Scanner where we are getting a single input from the user. Here, we are asking for a string through in.nextLine() method.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Watch this recorded lecture for explanation.