繁体   English   中英

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

[英]java exception handling - divide by zero and divide by text method

我已经从事Java 4个月了,所以我还是一个业余爱好者。 只是想完成一些任务。 似乎找不到正确的技巧来使我的分母通过拒绝文本数据和零而又保持与错误消息的循环来正常工作。 另一个问题是,无论我的分子/分母是多少,我的商都是0.0。 很多问题,任何建议都值得赞赏。 指示如下:

-该程序接受用户输入的(int)分子和(int)分母,然后计算并显示(double)商。

-如果用户输入文本而不是分子的数字,则显示一条错误消息以说明该问题,并使用户处于循环状态,直到输入正确的数据为止。

-如果用户输入文本或分母而不是数字,则输入零,则显示一条错误消息以说明问题,并使用户保持循环状态,直到输入正确的数据为止。

-有关问题的消息应具有描述性。

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;
}
}

商“ r”始终为0.0的事实是因为您将n1初始化为0且n2 = 1。 您应该只声​​明变量,然后在代码中将其初始化。 即,当您想从用户那里获取值时。

您的代码有很多问题。

对于初学者,您应该只有一个Scanner ,它将在应用程序的整个生命周期中都存在。 无需实例化多个扫描仪。

public class SomeClass {

    private static Scanner console;

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

        console = new Scanner(System.in);

        (...)

        console.close();
    }
}

现在,让我们看一下有问题的getInteger2方法。

如果输入是整数,则应该像对getInteger方法一样简单地进行验证。 如果是,则进行处理。 否则,您要使用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;
}

最后,您的商总是被打印为0.0因为您在输出它之前不会更新它的值:

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

看来您的代码/逻辑中有两个“主要”问题。

问题1)获取输入后,您没有计算r (商)。

因此,这些行: } catch (InputMismatchException ime) { } 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);

问题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; 如果您不想在代码中进行太多更改,可以将其更改为以下内容: 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; 因此,仅当console的输入为int ,才使用nextInt()读取它并将其存储在count 在您的代码中,您将使用nextInt()读取int ,如果是int ,则可以使用nextInt()再次读取int ,这将导致用户写入2个int以及您在检查之前读取int问题它是一个导致引发InputMismatchExceptionint 在我发送给您的代码中,如果读取的数字是int而不是0 ,则返回该数字,如果它是0 ,则您的循环再次运行,如果它根本不是int ,则再次简单地调用该方法(请参阅递归) )。 希望这可以帮助您了解问题。 但是,最好的方法可能是重新设计代码。

暂无
暂无

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

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