Java User Input

In Java, you can get user input using various classes like Scanner and BufferedReader. These classes are part of the Java API and allow you to read data from different input streams, such as the console or files.

1. Using the Scanner Class

The Scanner class is the most commonly used class for reading user input from the console.

Example: Reading a String

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");
        scanner.close();
    }
}

2. Reading Different Data Types

The Scanner class provides methods to read different data types.

  • nextInt() - Reads an integer
  • nextDouble() - Reads a double
  • nextLine() - Reads a line of text

Example: Reading an Integer

System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");

3. Using BufferedReader

BufferedReader can also be used to read user input, although it requires handling exceptions.

Example: Reading a String

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your name: ");
        String name = reader.readLine();
        System.out.println("Hello, " + name + "!");
    }
}

4. Key Takeaways

  • The Scanner class is the easiest way to read user input from the console.
  • Always close the Scanner after use to free resources.
  • Handle exceptions when using BufferedReader.
  • Choose the appropriate class based on the input source and requirements.