;

Java Program to Print an Integer Entered by the User


Tutorialsrack 19/04/2021 Java

In this Java Program, you will learn how to print an Integer entered by the user. The integer is stored in a variable using System.in, and is displayed on the monitor display using System.out.

Java Program to Print an Integer Entered by the User

Java Program to Print an Integer Entered by the User
//Java Program to Print an Integer Entered by the User

import java.util.Scanner;

public class PrintInteger {

	public static void main(String[] args) {

        // Creates a reader instance which takes
        // 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() prints the following line to the output screen
        System.out.println("You entered the Number: " + number);
    }
}
Output

Enter a number: 222

You entered the Number: 222

Understand the Program

  • In the above program, an object of Scanner class, the reader is created to take inputs from standard input, which is the keyboard.
  • Then, Enter a number prompt is printed to give the user a visual cue as to what they should do next.
  • reader.nextInt() then reads all entered integers from the keyboard unless it encounters a newline character \n using Enter Key. The entered integers are then saved to the integer variable number.
  • If you enter any character which is not an integer, then the compiler will throw an exception which is InputMismatchException.

Finally, the number is printed onto the standard output (System.out) - computer display using the function println().


Related Posts



Comments

Recent Posts
Tags