How to Take Input From User in Java

Whether you are writing console programs or solving problems in Java, one of the common needs is to take input from the user. For console programs, you need to have access to the command line. Java has a utility class named Scanner which is capable of getting typed input from user. This class can directly convert user input to basic types such as int, float and String.

The following example program demonstrates the use of java.util.Scanner for getting user input from command line. It asks for user’s name and age and then prints it back. Note the automatic conversion of age to the int variable. This is what makes Scanner so useful.

import java.util.Scanner;

/** This example program demonstrates how to get user input from commandline in Java */
public class UserInput {
    public static void main(String[] args) {
        UserInput ui = new UserInput();

    /** Takes a number of inputs from user and then prints it back */
    private void getInputAndPrint() {
        Scanner scn = new Scanner(;
        System.out.print("Please enter your name: ");
        String name = scn.nextLine();
        System.out.print("Please enter your age: ");
        int age = scn.nextInt();
        System.out.println("Hello "+name+"! "+ "You are "+age+" years old.");

Please note that the scanner methods throw InputMismatchException exception if it doesn’t receive the expected input. For example, if you try to enter alphabets when you called nextInt() method.

Scanner has methods such as nextInt, nextFloat, nextByte, nextDouble, nextBigDecimal, etc. to directly read typed data from command line. To read a line of String, use nextLine method. Scanner also has a generic next method to process an input which can be defined using a regular expression. If the input doesn’t match the regular expression, InputMismatchException is thrown.

The following code demonstrates the use of restricting the user input to a regular expression pattern,

private void get4DigitNumber() {
        Scanner scn = new Scanner(;
        String s = "";
        Pattern p = Pattern.compile("\\d\\d\\d\\d");//get 4 digit number 
        System.out.print("Please enter a 4 digit number: ");
        try {
             s =;
             System.out.println("4digit number is: "+s);
         }catch(InputMismatchException ex) {
             System.out.println("Error! Doesn't match the pattern");

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.

Leave a Reply