Here we are explaining how to write a java program to read an integer number from the user and print it. In java, we can read an integer number from the user by using the scanner class object.
Scanner class is a java class in java. util package. For using the Scanner class we have to import the java. util package. To read an integer number from the user we have to use the nextInt() function of the Scanner class in java. an example is shown below.
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
Here first we create an object of the scanner class as a scan.Then read the integer number as sc.nextInt();
First, we have to declare the class ReadNum.Create an object of the scanner class as sc. Then read an integer number from the user using nextInt() method into the variable a.Then close the scanner class object as sc.close(). By using System.out.println()
function display the integer number entered by the user as a.
STEP 1: Declare the class ReadNum with a public modifier.
STEP 2: Open the main() to start the program, Java program execution starts with the main()
STEP 3: Create an object of the scanner class as sc.
STEP 4: Read a number from the user into the variable a.
STEP 5: Close the scanner class object.
STEP 6: Display the number a by using System.out.println()
.
import java.util.Scanner;
public class ReadNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int a = sc.nextInt();
sc.close();
System.out.println("The number you entered is: "+a);
}
}
Enter the number: 100 The number you entered is: 100