You can use Scanner class
To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.
Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.
- To create an
objectofScannerclass, we usually pass the predefined objectSystem.in, which represents the standard input stream (Keyboard).
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Some Public methods in Scanner class.
hasNext()Returns true if this scanner has another token in its input.nextInt()Scans the next token of the input as an int.nextFloat()Scans the next token of the input as a float.nextLine()Advances this scanner past the current line and returns the input that was skipped.nextDouble()Scans the next token of the input as a double.close()Closes this scanner.
For more details of Public methods in Scanner class.
ExapleExample:-
import java.util.Scanner; //importing class
class ScannerTest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // Scanner object
System.out.println("Enter your rollno");
int rollno = sc.nextInt();
System.out.println("Enter your name");
String name = sc.next();
System.out.println("Enter your fee");
double fee = sc.nextDouble();
System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
sc.close(); // closing object
}
}