top of page

How to read User Input from Console in Java?

Updated: Jul 26, 2022



Let's see a complete code example of reading user input using the Scanner class. In this Java program, we are reading User Input in form of String using Scanner's nextLine() method and numbers particular integer using nextInt() method of Scanner.


The scanner is created by passing System.in which is an InputStream as a source which means it will scan input console for data.


And, here is our complete Java program to demonstrate how to read user input from the command prompt using the Scanner class in Java.



Example:

public class UserInputExample {

    public static void main(String args[]) {
 
        //Creating Scanner instance to scan console for User input
        Scanner console = new Scanner(System.in);
   
        System.out.println("System is ready to accept input, please enter name : ");
        String name = console.nextLine();
        System.out.println("Hi " + name + ", Can you enter an int number now?");
        int number = console.nextInt();
        System.out.println("You have entered : " + number);
        System.out.println("Thank you");
     
    }   
}

Output:

The system is ready to accept input, please enter the name :
John
Hi John, Can you enter an int number now?
56
You have entered: 56
Thank you


The scanner allows you to read various types of input directly from the User without extra conversion e.g. you can read int, float, long, double, or String directly.




Source: Java67.com


The Tech Platform

0 comments

コメント


bottom of page