0

I am a beginner in Java and currently learning exceptions using the try-catch block

I have 5 variables that need user input and I want to create a try-catch block for each variable and when input a wrong data type or value, I want the code to ask the user for a correct input for that specific variable. This code is just a part of a while loop with runProgram = true '''

try {
  boolean run = true;
  while(run) {
    System.out.println("please enter make: ");
    make = input.next();        
    run = false;                                
      }
    }catch(Exception e) {
      System.out.println("Wrong input try again");
    }
                    
try {
  boolean run = true;
  while(run) {
    System.out.println("please enter model: ");
    model = input.next();
    run =false;                         
      }
    }catch(Exception e) {
      System.out.println("Wrong input try again");
    }
                    
try {
  boolean run =true;
  while(run) {
    System.out.print("Enter year: ");
    year = input.nextInt();
    run = false;
      }
    }catch(Exception e) {
      System.out.println("Wrong input try again: ");
    }

'''

On the input for year variable, after typing a wrong input, the output:
Wrong input try again:
please enter make:
please enter model:

After inputting wrong input, I need to ask for a correct input instead input wrong data type, not int
Wrong input try again
Enter Year:

Csparkx
  • 1
  • 2

0 Answers0