Logo

Developer learning path

Java

Reading user input in Java

Reading user input

52

#description

Java is a programming language that allows developers to create software applications that can interact with users. To create interactive applications, developers need to read user input from the computer's keyboard or mouse. Input can be anything, from numbers to text, and Java provides several ways to take input from the user.

One of the most commonly used ways to take user input in Java is the Scanner class. The Scanner class provides methods to read input from various sources, including keyboards, files and sockets. To use the Scanner class, you need to create an object of the Scanner class, and then use its methods to take user input.

Here's an example of how you can take user input using the Scanner class:

                    
import java.util.Scanner;

public class UserInput {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("Enter your name: ");
      String name = scanner.nextLine();
      System.out.println("Your name is "+name);
      
      System.out.println("Enter your age: ");
      int age = scanner.nextInt();
      System.out.println("Your age is "+age);
   }
}
                  

In the code above, we created a Scanner object called scanner and used its nextLine() method to read the user's name and its nextInt() method to read the user's age. The user input is then printed to the console using the System.out.println() method.

The Scanner class is just one way to take user input in Java. There are several other ways, including reading input from the console using the BufferedReader class, taking input from GUI components, and reading input from files.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.