简体   繁体   中英

try catch exception while loop

I would like the program to re-do the while loop when it catches the exception - the exception being receiving a number zero. Instead it continues a while loop with the code below, I would like it to ask for the user input again until the user inputs a number that is different by zero.

import java.util.InputMismatchException;
import java.util.Scanner;

public class whilePerjashtim {

    public static int division(int a, int b){

        return a/b;
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        int a, b;

        System.out.println("Enter a value: ");
        a = s.nextInt();

    while(true){

        try
        {

            System.out.println("Enter b value");
            b = s.nextInt();

            System.out.println("Sum of division is: " + division(a,b));


        }

        catch(ArithmeticException e) 
        {
            System.err.println("Don't divide by zero!!!");      
        }

        catch (java.util.InputMismatchException e)
        {
            System.err.println("Enter just a Number!!!");
        }

        finally
        {
            System.out.println();
        }

    }

    }
}

Use something of the following form (not exact Java for your homework problem)

 boolean validInput = false;
 while (!validInput) {
    .. get input
       .. set validInput = true if no error
    .. catch error 
       .. print try again message
 }

You can set a boolean value, that determines, if the while loop ends succesfully. Then in every loop you start by assuming the value is true and when an exception is raised, you set it to false .

boolean success = false;

while(success == false){
    success = true;
    try {
        System.out.println("Enter b value");
        b = s.nextInt();
        System.out.println("Sum of divison is: " + division(a,b));
    }

    catch(ArithmeticException e) {
        System.err.println("Dont divide by zero!!!");
        success = false;   
    }
}

Define a boolean outside of your while loop, and use it for the while's condition.

Assuming I understood your question correctly, you want to stay in the loop if the user's input threw an exception, ie it was invalid input, and you want to break out of the loop when you get valid input from the user.

boolean gotValidInput = false;
while (!gotValidInput) {
    try {

        System.out.println("Enter b value");
        b = s.nextInt();
        gotValidInput = true;
        System.out.println("Sum of divison is: " + division(a,b));


    } catch(ArithmeticException e) {
        System.err.println("Dont divide by zero!!!");       
    } catch (java.util.InputMismatchException e) {
        System.err.println("Enter just a Number!!!");
    } finally {
        System.out.println();
    }
}

In this implementation, your two exceptions would both be thrown before gotValidInput = true; gets evaluated, so it would only get set to true if no exceptions were thrown.

You can put extra outter loop, like

    while (true) {
      System.out.println("Enter a value: ");
      a = s.nextInt();
      while(true) {


        /// terminate the loop in case of problem with a, and allow a user to re done
      }
    }

Cleaned up the warnings and moved s to ouside the main method and defined it as static . It appears the s is a resource leak if within the main and is never closed.

import java.util.InputMismatchException;
import java.util.Scanner;

public class whilePerjashtim {

    private static Scanner s;

    public static int division(int a, int b) {

        return a / b;
    }

    public static void main(String[] args) {

        int a, b;

        s = new Scanner(System.in);

        System.out.println("Enter a value: ");
        a = s.nextInt();

        boolean input = false;

        while (input == false) {

            try {

                System.out.println("Enter b value");
                b = s.nextInt();

                System.out.println("Sum of division is: " + division(a, b));

                input = true;
            }

            catch (ArithmeticException e) {
                System.err.println("Don't divide by zero!!!");
            }

            catch (InputMismatchException e) {
                System.err.println("Enter just a Number!!!");
            }

            finally {
                System.out.println();
            }

        }

    }
}

You need to handle the erroneous input as well if you want the while loop to continue properly: You need to get rid of the erroneous input at the end of each catch block. Adding continue will simply make the loop run again until the user gives the correct input.

catch (InputMismatchException e)
{
    System.err.println("Enter just a Number!!!");
    //add this
    s.nextLine();
    continue;
}

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