Created
April 12, 2023 04:28
-
-
Save greenido/800090d430efb3270821e39801efc812 to your computer and use it in GitHub Desktop.
This program asks the user for their name, age, and favorite color. It then prints a report to the console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
/** | |
* This program asks the user for their name, age, and favorite color. | |
* It then prints a report to the console. | |
*/ | |
public class QA { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
// Ask the user for three questions and store the answers | |
System.out.print("What is your name? "); | |
String name = scanner.nextLine(); | |
// Let's validate that the user entered a valid age | |
int age = 0; | |
boolean validAge = false; | |
while (!validAge) { | |
System.out.print("What is your age? "); | |
String ageString = scanner.nextLine(); | |
try { | |
age = Integer.parseInt(ageString); | |
if (age > 0 && age < 120) { | |
validAge = true; | |
} | |
else { | |
throw new NumberFormatException(); | |
} | |
} catch (NumberFormatException e) { | |
System.out.println("Invalid input. Please enter a valid number for an age, ok? \n"); | |
} | |
} | |
scanner.nextLine(); // consume the remaining newline | |
System.out.print("What is your favorite color? "); | |
String favoriteColor = scanner.nextLine(); | |
// Print the report to the console | |
System.out.println("\n\n The Report:"); | |
System.out.println("Name: " + name); | |
System.out.println("Age: " + age); | |
System.out.println("Favorite color: " + favoriteColor); | |
scanner.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment