Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a number: "); int number = reader.nextInt(); System.out.println("You entered: " + number); } } |
Output:
1 2 3 4 | Enter a number: 123 You entered: 123 |
Scanner class reader is used to created to take inputs from standard input, which is keyboard.
reader.nextInt() reads all entered integers from the keyboard unless it encounters a new line character \n (Enter).
If you enter any character which is not an integer, the compiler will throw an InputMismatchException.