简体   繁体   中英

Do while loop with try catch

public static void main(String[] args) throws IOException {

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);

    boolean format = false;
    int grades = 0;

    do {
        System.out.println("Enter course mark (0-100): ");

        try {
            String input = br.readLine();
            grades = Integer.parseInt(input);

        } catch (NumberFormatException | IOException e) {
            System.out.println("Error number format!");
        }

    } while (!format);

    if (grades > 100 || grades < 100) {
        System.out.println("Please enter within the range (0-100)");
    }

    System.out.println("Your grades is " + grades);

}

What have i done wrong here i am trying to achieve this

Enter course mark (0-100): qwerty
Bad input data type.
Enter course mark (0-100): -12
Input out of [0, 100] range!
Enter course mark (0-100): 24
Your grades is 24

Change

do {
    try {
        String input = br.readLine();
        grades = Integer.parseInt(input);
    }
    catch(...) { ... }
} while (!format);

to

do {
    try {
        String input = br.readLine();
        grades = Integer.parseInt(input);
        format = true; // Add this line
    }
    catch(...) { ... } 
    if (grades > 100 || grades < 100) {
        System.out.println("Please enter within the range (0-100)");
        format = false;
    }

} while (!format);

If the execution flow reaches format = true; , then that means that the user's input was correct & will make sure that you break the input loop.

You no need to use the do..while block.the output is possible with While block itself. You can also change your program block like this

public static void main(String[] args) throws IOException 
{
    int grades = 0;
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr)
while((input=br.readLine())!=null)
    {
      try 
          {
           grades = Integer.parseInt(input);
          }
      catch (NumberFormatException | IOException e) 
          {
           System.out.println("Error number format!");
          }
    }

    if (grades > 100 || grades < 100) 
       {
        System.out.println("Please enter within the range (0-100)");
       }

 System.out.println("Your grades is " + grades);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM