In Java programming, interacting with users and obtaining input is a common requirement for many applications. Whether you’re building a command-line tool, a simple text-based game, or a complex interactive program, the ability to get user input is essential. In this blog post, we will explore how to get user input using the Scanner class in Java.
Incorporating user input into your code might be something you’re wondering about if you’re new to Java programming. Fortunately, Java offers a built-in class called Scanner that makes it simple to receive input from the user.
Following code demonstrates how to use the Scanner class to get the user name and age:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("What is your name?");
String name = scanner.nextLine();
System.out.println("How old are you? (Please enter a positive number)");
int age = scanner.nextInt();
if (age < 0) {
System.out.println("Invalid age entered. Please enter a positive number.");
return;
}
System.out.printf("Your name is %s,\nand you are %d years old.", name, age);
}
}
}
I do sincerely hope you find this helpful. If you wish to learn more about Java, please subscribe to our newsletter today and continue your Java learning journey with us!