java

How to Get User Input in Java

In this tutorial, we are going to see how to get user input in Java. Reading keyboard input in Java is done using a Scanner object.

Consider the following statement:

Scanner sc = new Scanner(System.in)

This statement declares a Scanner object named “sc”. The Scanner object is associated with a standard input device (System.in).

To get input from the keyboard, you can use methods of the Scanner class. For example, nextInt() method used to read an integer, nextChar() method used to read a character. The method takes the input and returns it to a variable:
 

 
Example to read an integer:

int x = sc.nextInt();

Example to read a character:

int x = sc.nextChar();

 

Complete Example :
import java.util.Scanner;

public class Person
{
    public static void main(String[] args)
    {
        String name;
        int age; 

        //Create a Scanner object to read the input
        Scanner console = new Scanner(System.in);

        // Get the person's name
        System.out.print("Enter your name: ");
        name = console.nextLine();

        // Get the person's age
        System.out.print("Enter your age: ");
        age = console.nextInt();

        // Display information of the person
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

 
Output:

Enter your name: Alex
Enter your age: 25
Name: Alex, Age: 25
 
Some other useful methods of the Scanner class:

The method
The return value
nextInt() It is used to read an integer value on the keyboard.
nextFloat() It is used to read a floating point number on the keyboard.
nextLong() It is used to read a long value on the keyboard.
next() It is used to read a string of characters on the keyboard.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *