简体   繁体   English

Java异常处理-除以零并除以文本方法

[英]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. 我已经从事Java 4个月了,所以我还是一个业余爱好者。 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. 另一个问题是,无论我的分子/分母是多少,我的商都是0.0。 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. -该程序接受用户输入的(int)分子和(int)分母,然后计算并显示(double)商。

--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; 商“ r”始终为0.0的事实是因为您将n1初始化为0且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. 对于初学者,您应该只有一个Scanner ,它将在应用程序的整个生命周期中都存在。 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. 现在,让我们看一下有问题的getInteger2方法。

You should simple validate, as you do on your getInteger method, if the input is an integer. 如果输入是整数,则应该像对getInteger方法一样简单地进行验证。 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. 否则,您要使用next() (而不是nextLine() )跳过它,因为您想跳过此扫描器的下一个完整令牌。

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: 最后,您的商总是被打印为0.0因为您在输出它之前不会更新它的值:

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. 问题1)获取输入后,您没有计算r (商)。

So the lines: } catch (InputMismatchException ime) { } System.out.println("Fraction result is " + r); 因此,这些行: } 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); } 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; 问题2)您的代码: 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; 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 . 因此,仅当console的输入为int ,才使用nextInt()读取它并将其存储在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. 在您的代码中,您将使用nextInt()读取int ,如果是int ,则可以使用nextInt()再次读取int ,这将导致用户写入2个int以及您在检查之前读取int问题它是一个导致引发InputMismatchExceptionint 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 ). 在我发送给您的代码中,如果读取的数字是int而不是0 ,则返回该数字,如果它是0 ,则您的循环再次运行,如果它根本不是int ,则再次简单地调用该方法(请参阅递归) )。 I hope this helps you understand the issues. 希望这可以帮助您了解问题。 The best way, however, would probbaly be do redesign your code a bit. 但是,最好的方法可能是重新设计代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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