Exercise:
Write a Java Program that prints an Integer entered by the user.
Click Here to View the Solution!
// Required import statement to use nextInt()
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// prompt user for input
System.out.print("Enter an Integer: ");
// nextInt() is the built-in method that reads
// the next integer from the keyboard
int num = input.nextInt()
// println() is the built-in method that
// prints the following line to the console screen
System.out.println("Integer entered = " + num);
}
}
Click Here to View the Output!
Enter an Integer: 23 Integer entered = 23
Click Here to View the Explanation!
- This program consists of two parts. Taking input and displaying the output on the screen. In the first part
reader
object ofScanner
class is created to take input from standard input device, which is the keyboard. "Enter an Integer: "
is displayed via aprint()
statement to prompt the user to take action.- A variable number is already initiated to store the input in it.
reader.nextInt()
is the built in function that reads all the entered integers and stores them in the variable number until\n (Enter)
is encountered. Eventually the entered number will be displayed on console screen using the functionprintln()
. - Note : If a user enter any data type other than an integer, the compiler will show an
InputMismatchException
.