English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Java Examples
In this program, you will learn to print the number entered by the user in Java. The integer is stored in the variable using System.in and displayed on the screen using System.out.
import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { //Create an instance of a reader //Input from standard input-Keyboard Scanner reader = new Scanner(System.in); System.out.print("Enter a number: "); //nextInt() reads the next integer from the keyboard int number = reader.nextInt(); //println() will print the following line to the output screen System.out.println("You entered: ", + number); } }
When the program is run, the output is:
Enter a number: 10 You entered: 10
In this program, an object of the Scanner class reader is created to obtain input from the standard input (i.e., the keyboard).
Then, 'Enter a number' will print a prompt to provide the user with a visual hint about the next operation.
Then, reader.nextInt() will read all the integers entered from the keyboard, unless a newline character \ n (Enter) is encountered. Then, the entered integers are saved to the integer variable number.
If the input character is not an integer, the compiler will throw an InputMismatchException.
Finally, use the function println() to print the number to the standard output (System.out) computer screen.