In this program we will see how to read an integer number entered by user. Scanner class is in java.util package. It is used for capturing the input of the primitive types like int, double etc. and strings.
Example: Program to read the number entered by user
We have imported the package java.util.Scanner
to use the Scanner. In order to read the input provided by user, we first create the object of Scanner by passing System.in
as parameter. Then we are using nextInt() method of Scanner class to read the integer. If you are new to Java and not familiar with the basics of java program then read the following topics of Core Java:
→ Writing your First Java Program
→ How JVM works
import java.util.Scanner; public class Demo { public static void main(String[] args) { /* This reads the input provided by user * using keyboard */ Scanner scan = new Scanner(System.in); System.out.print("Enter any number: "); // This method reads the number provided using keyboard int num = scan.nextInt(); // Closing Scanner after the use scan.close(); // Displaying the number System.out.println("The number entered by user: "+num); } }
Output:
Enter any number: 101 The number entered by user: 101
Leave a Reply