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 thejava.util
package. - Inside the
main()
method, we create a newScanner
object namedscanner
that reads input from the console. - We output a prompt to the console using the
System.out.print()
method and then use thescanner.nextLine()
method to read the user’s input into aString
variable namedname
. - We output another prompt to the console using the
System.out.print()
method and then use thescanner.nextInt()
method to read the user’s input into anint
variable namedage
. - 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.