Java Program to Get Input from User

In Java, you can use the Scanner class to get input from the user via the console. In this article, we will discuss how to write a Java program that gets input from the user.

Here is an example Java program that prompts the user to enter their name and age, then outputs a message with their information:

import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Hello, " + name + "! You are " + age + " years old.");
    }
}

Let’s break down this code line by line.

  • The first line imports the Scanner class from the java.util package.
  • Inside the main() method, we create a new Scanner object named scanner that reads input from the console.
  • We output a prompt to the console using the System.out.print() method and then use the scanner.nextLine() method to read the user’s input into a String variable named name.
  • We output another prompt to the console using the System.out.print() method and then use the scanner.nextInt() method to read the user’s input into an int variable named age.
  • Finally, we output a message to the console using the System.out.println() method that includes the user’s name and age.

When we run this program, it will prompt the user to enter their name and age. After the user enters their information and presses Enter, the program will output a message with their information.

Enter your name: John Doe
Enter your age: 30
Hello, John Doe! You are 30 years old.

This program demonstrates how to get input from the user in Java using the Scanner class. By understanding the basics of Java syntax and input/output, you can create more interactive programs that work with user input.