How to get user input in Java?

QuestionsQuestions8 SkillsProYour First Python LabNov, 01 2025
087

In Java, you can get user input using the Scanner class. Here's a simple example:

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        // Create a Scanner object
        Scanner scanner = new Scanner(System.in);

        // Prompt the user for input
        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Read user input

        // Display the input
        System.out.println("Hello, " + name + "!");

        // Close the scanner
        scanner.close();
    }
}

In this code:

  • Scanner scanner = new Scanner(System.in); creates a new Scanner object to read input from the console.
  • scanner.nextLine(); reads a line of text entered by the user and stores it in the variable name.
  • Finally, the program greets the user with their name.

Feel free to ask if you have more questions about Java or user input!

0 Comments

no data
Be the first to share your comment!