In this java program, we will learn about how to take an integer input from user and print it on screen. We will also learn about Scanner class, which is widely used for taking the input of basic data types like char, int, double etc from user.
To understand this java program, you should have understanding of the following Java programming concepts:
Java Program to Print an Integer Entered by User
import java.util.Scanner; public class PrintInteger { public static void main(String[] args) { int number; Scanner scanner = new Scanner(System.in); System.out.println("Enter an Integer"); // Take input from user number = scanner.nextInt(); // Print the number entered by user System.out.println("Integer Input: " + number); } }Output
Enter an Integer 25 Integer Input: 25
To take any input using Scanner class, we have to first import Scanner class as
import java.util.Scanner;
Scanner class in part of java.util package, which is s widely used for taking the input of basic data types like char, int, double etc from user. It breaks the keyboard input into tokens using a specified delimiter or using whitespace as default delimiter. It provide various method to parse basic data types from input.
- In above java program, first of all we defined an integer variable "number" to save the user input.
- An object of Scanner class "scanner" is created to take input from standard input (keyboard) by passing "System.in".
- We print "Enter an Integer" message on screen asking user to enter an integer number.
- To read an integer from keyboard, we call nextInt() method of scanner object, which parses the next input token as an integer value and return it.
- If user enters anything else other than an integer, then compiler will throw an InputMismatchException.
- At last, we print the number entered by the user on standard output(screen) using System.out.println() method.