【问题标题】:Why am I getting java.lang.ArithmeticException: / by zero?为什么我得到 java.lang.ArithmeticException: / 为零?
【发布时间】:2016-03-29 22:04:56
【问题描述】:

我是 java 初学者,我生成随机和的代码抛出了一个奇怪的异常...

    public void randomRekensom(int n)
{

    switch(n) {
        case 1: this.max = 100;
                break;
        case 2: this.max = 150;
                break;
        case 3: this.max = 200;
                break;
}
    getal1= (int) Math.sqrt(max);
    getal2= (int) Math.sqrt(max);

    operator=ThreadLocalRandom.current().nextInt(1, 4 + 1);
    switch(operator) {
        case 1: antwoord=(this.getal1+this.getal2);
                operatorTeken=" + ";
                break;
        case 2: antwoord=(this.getal1-this.getal2);
                operatorTeken=" - ";
                break;
        case 3: antwoord=(this.getal1/this.getal2);
                operatorTeken=" / ";
                break;
        case 4: antwoord=(this.getal1*this.getal2);
                operatorTeken=" * ";
                break;
}

}

也许是因为我今天盯着屏幕看太多了,但我不知道为什么会出现这个错误。

提前致谢!

【问题讨论】:

  • 错误信息说你除以零。
  • 我猜n既不是1、2也不是3。
  • 这段代码运行前max是什么?
  • 谢谢,我太用力了,它是从另一个类调用的,你的评论让我再次查看了我的代码,抱歉这个简单的问题。

标签: java greenfoot


【解决方案1】:

只有在n 是 1、2 或 3 时才设置 this.max。如果您之前没有将它设置为其他值,this.max == 0,所以getal2 == Math.sqrt(0) == 0

您应该在switch 语句中添加default 大小写,以处理n 的所有其他值。简单地抛出一个IllegalArgumentException 可能是合适的。

switch(n) {
    case 1: this.max = 100;
            break;
    case 2: this.max = 150;
            break;
    case 3: this.max = 200;
            break;
    default: throw new IllegalArgumentException("Not 1, 2 or 3");
}

或者您可能有一个合理的默认值,您可以将其设置为this.max

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多