import java.util.Scanner;
public class ConfigInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// User input for name
String name = getUserInput("Enter your name: ");
// Validate name (handle empty string)
if (name == null || name.trim().isEmpty()) {
System.out.println("Error: Name cannot be empty. Exiting.");
return; // Exit if name is invalid
}
// User input for age
int age = getIntInput("Enter your age: ");
// Validate age (handle negative values)
if (age < 0) {
System.out.println("Error: Age cannot be negative. Exiting.");
return;
}
// User input for email
String email = getUserInput("Enter your email: ");
// Validate email (basic check for @ symbol)
if (email == null || email.trim().isEmpty() || !email.contains("@")) {
System.out.println("Error: Invalid email format. Exiting.");
return;
}
// User input for city
String city = getUserInput("Enter your city: ");
//Validate city (handle empty string)
if (city == null || city.trim().isEmpty()) {
System.out.println("Error: City cannot be empty. Exiting.");
return;
}
// Print the configuration
System.out.println("\nConfiguration:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
System.out.println("City: " + city);
scanner.close();
}
// Helper function to get string input with prompt
public static String getUserInput(String prompt) {
System.out.print(prompt);
return scanner.nextLine(); // Read the entire line
}
// Helper function to get integer input with prompt
public static int getIntInput(String prompt) {
System.out.print(prompt);
try {
return Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Invalid integer input. Exiting.");
return -1; // Indicate an error
}
}
}
Add your comment