-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserInputExample.java
More file actions
34 lines (29 loc) · 1.18 KB
/
UserInputExample.java
File metadata and controls
34 lines (29 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine().trim();
System.out.print("Enter your age in years: ");
int age = readInt(scanner);
System.out.print("Enter your favorite number: ");
int favorite = readInt(scanner);
int yearsToHundred = Math.max(0, 100 - age);
System.out.println();
System.out.println("Hi, " + name + "!");
System.out.println("You will hit 100 in " + yearsToHundred + " year(s).");
System.out.println("Your favorite number doubled is " + (favorite * 2) + ".");
}
}
// Loop until the user enters a valid integer.
private static int readInt(Scanner scanner) {
while (true) {
String line = scanner.nextLine().trim();
try {
return Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.print("Please enter a valid whole number: ");
}
}
}
}