简体   繁体   中英

java exception handling - divide by zero and divide by text method

I've been doing java for 4 months, so I'm still an amateur. Just trying to get some hwk done. Can't seem to find the right tips for getting my denominator to function well by rejecting text data and zero while keeping in a loop with error messages. Another issue is the fact my quotient is 0.0 no matter what my numerator / denominator is. Lots of problems, any advice is appreciated. Directions are as follows:

--This program takes user input for a (int) numerator and (int) denominator then computes and displays the (double) quotient.

--If the user enters text instead of number for the numerator, display an error message explaining the issue and keep user in a loop until the correct data is entered.

--If the user enters text or a zero instead of a number for the denominator, display an error message explaining the issue and keep user in a loop until the correct data is entered.

--Messages should be descriptive with respect to the issue.

public static void main(String[] args) throws Exception {
    Scanner console = new Scanner(System.in);
    int n1 = 0; //number 1
    int n2 = 1; //number 2..
    double r = (double) n1 / n2; //quotient
    String n1Str = "Please enter a real number for the numerator";
    String n2Str = "Please enter a real number greater than zero for the denominator";
    String errMsg = "Please enter a real number.";
    String notZero = "Denominator cannot equal zero.";      // not all string msgs are used, just there in case i need them.

    try {
        n1 = getInteger(n1Str); // validates against alphabet
        if (hasNextInt()) {     // working
            n1 = console.nextInt();
        }
    } catch (InputMismatchException ime) {
    }

    try {
        n2 = getInteger2(n2Str); // trying to validate against alphabet & zero
        if (hasNextInt()) {     //  not working though... 
            n2 = console.nextInt();
        }
    } catch (InputMismatchException ime) {
    }
    System.out.println("Fraction result is " + r);
}   

public static int getInteger(String message) {
    Scanner console = new Scanner(System.in);
    int count = 0;
    boolean isValidInteger = false;
    do {
        System.out.println(message);
        if (console.hasNextInt()) {
            isValidInteger = true;
            count = console.nextInt();
        } else {
            console.nextLine();
        }
    } while (!isValidInteger);
    return count;
}

public static int getInteger2(String message) {
    Scanner console = new Scanner(System.in);
    int count = 0;
    boolean isValidInteger = false;

    do {
        System.out.println(message);
        if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but 
            isValidInteger = true;              // can't get it to validate against text.
            count = console.nextInt();  //tried switching statements and using && but get thrown into endless loop
        }
    } while (!isValidInteger);
    return count;
}

private static boolean hasNextInt() {
    return false;
}
}

The fact that your quotient "r" is always 0.0 is because you initialize n1 to be 0 and n2=1; You should just declare the variables and initialize them down in your code; ie when you want to get the values from the user.

You have lots of issues with your code.

For starters, you should have only one Scanner , that would exist throughout the lifespan of your application. There's no need to instantiate multiple scanners.

public class SomeClass {

    private static Scanner console;

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

        console = new Scanner(System.in);

        (...)

        console.close();
    }
}

Now lets look into your problematic getInteger2 method.

You should simple validate, as you do on your getInteger method, if the input is an integer. If it is, you process it; otherwise, you skip it using next() (not nextLine() ) since you want to jump over the next complete token from this scanner.

public static int getInteger2(String message) {
    int count = -1;

    boolean isValidInteger = false;

    do {
        System.out.println(message);

        if (console.hasNextInt()) {
            count = console.nextInt();

            if (count != 0) {
                isValidInteger = true;
            } else {
                System.out.println("Denominator cannot equal zero.");
            }
        } else {
            console.next();
        }
    } while (!isValidInteger);

    return count;
}

Finally, your quotient is always being printed 0.0 since you're not updating its value before outputting it:

r = (double) n1 / n2;
System.out.println("Fraction result is " + r);

It seems that you have two "main" problems in your code/logic...

Problem 1) You are not calculating r (your quotient) after you get the inputs.

So the lines: } catch (InputMismatchException ime) { } System.out.println("Fraction result is " + r); could be changed to something like: } catch (InputMismatchException ime) { } r = (double) n1 / n2; //calculate the quotient System.out.println("Fraction result is " + r); } catch (InputMismatchException ime) { } r = (double) n1 / n2; //calculate the quotient System.out.println("Fraction result is " + r);

Problem 2) Your code: do { System.out.println(message); if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but isValidInteger = true; // can't get it to validate against text. count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop } } while (!isValidInteger); return count; do { System.out.println(message); if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but isValidInteger = true; // can't get it to validate against text. count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop } } while (!isValidInteger); return count; could be changed to something like this, if you don't want to change too much in your code: do { System.out.println(message); try { if ((count = console.nextInt()) != 0) { isValidInteger = true; } } catch (InputMismatchException ime) { return getInteger2(message); } } while (!isValidInteger); return count; do { System.out.println(message); try { if ((count = console.nextInt()) != 0) { isValidInteger = true; } } catch (InputMismatchException ime) { return getInteger2(message); } } while (!isValidInteger); return count; so that only if the input in console is an int you read it with nextInt() and store it in count . In your code you would read the int with nextInt() and if it is an int you read it again with nextInt() , which causes the user to write in 2 int s as well as your issue that you read the int before checking that it is an int which causes the InputMismatchException to be thrown. In the code I sent you, if the read number is an int AND not 0 then it is returned, if it is 0 your loop runs again and if it isn't an int at all the the method is simply called again (see Recursion ). I hope this helps you understand the issues. The best way, however, would probbaly be do redesign your code a bit.

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