1. import java.util.Scanner;
  2. public class ConfigInput {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. // User input for name
  6. String name = getUserInput("Enter your name: ");
  7. // Validate name (handle empty string)
  8. if (name == null || name.trim().isEmpty()) {
  9. System.out.println("Error: Name cannot be empty. Exiting.");
  10. return; // Exit if name is invalid
  11. }
  12. // User input for age
  13. int age = getIntInput("Enter your age: ");
  14. // Validate age (handle negative values)
  15. if (age < 0) {
  16. System.out.println("Error: Age cannot be negative. Exiting.");
  17. return;
  18. }
  19. // User input for email
  20. String email = getUserInput("Enter your email: ");
  21. // Validate email (basic check for @ symbol)
  22. if (email == null || email.trim().isEmpty() || !email.contains("@")) {
  23. System.out.println("Error: Invalid email format. Exiting.");
  24. return;
  25. }
  26. // User input for city
  27. String city = getUserInput("Enter your city: ");
  28. //Validate city (handle empty string)
  29. if (city == null || city.trim().isEmpty()) {
  30. System.out.println("Error: City cannot be empty. Exiting.");
  31. return;
  32. }
  33. // Print the configuration
  34. System.out.println("\nConfiguration:");
  35. System.out.println("Name: " + name);
  36. System.out.println("Age: " + age);
  37. System.out.println("Email: " + email);
  38. System.out.println("City: " + city);
  39. scanner.close();
  40. }
  41. // Helper function to get string input with prompt
  42. public static String getUserInput(String prompt) {
  43. System.out.print(prompt);
  44. return scanner.nextLine(); // Read the entire line
  45. }
  46. // Helper function to get integer input with prompt
  47. public static int getIntInput(String prompt) {
  48. System.out.print(prompt);
  49. try {
  50. return Integer.parseInt(scanner.nextLine());
  51. } catch (NumberFormatException e) {
  52. System.out.println("Error: Invalid integer input. Exiting.");
  53. return -1; // Indicate an error
  54. }
  55. }
  56. }

Add your comment