gpt4 book ai didi

java - 算术异常Java?

转载 作者:行者123 更新时间:2023-11-29 09:36:12 24 4
gpt4 key购买 nike

谁能帮我找到异常在哪里?我似乎找不到问题..

  public void fieldChanged(Field f, int context){
//if the submit button is clicked
try{
stopTime = System.currentTimeMillis();
timeTaken = stopTime - startTime;
timeInSecs = ((timeTaken/1000));
speed = 45/timeInSecs;
Dialog.alert("Speed of Delivery: " + speed + "mph");
}
catch(ArithmeticException e){
Dialog.alert("error " + speed);
e.printStackTrace();

}

}

startTime 变量是一个全局变量..

编辑:timeinSecs = 0 怎么可能?我似乎无法让我的调试器为 BlackBerry JDE 工作,所以必须有人帮助我 :( timeTaken 应该是以毫秒为单位的时间,从按下开始按钮到按下停止按钮的点......

所有其他变量也是全局变量

最佳答案

异常有类型,这允许您查找类型并快速对问题进行分类。来自文档:

ArithmeticException: Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

此外,大多数异常都是用一条消息构造的,以帮助您进一步弄清楚发生了什么。

try {
int i = 0 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}

这打印:

java.lang.ArithmeticException: / by zero
at [filename:line number]

但是这是怎么发生的?

Java 与许多其他编程语言一样,区分整数除法和 float 除法。

JLS 15.17.2 Division Operator /

The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor. Integer division rounds toward 0. [...] if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

如果您不熟悉整数除法,以下内容可能会让您感到惊讶:

    System.out.println(1/2); // prints "0"

这里发生的是,因为被除数和除数都是 int ,该操作是一个整数除法,其结果四舍五入为 int .请记住 int只能包含整数(范围有限,大约 40 亿个数字)。

您可以通过将至少一个操作数设为 float 来指定您需要浮点除法。

    System.out.println(1/2.0); // prints "0.5"
System.out.println(1D/2); // prints "0.5"

D是数字文字的特殊后缀,用于指定它是 double -精度值。还有 L对于 long (64 位整数)。

A double值需要存储在 double 中变量。

    double v = 1D / 2; // v == 0.5
int i = 1D / 2; // DOESN'T COMPILE!!! Explicit cast needed!

请注意,执行哪个除法与它最终将转到什么类型没有任何关系。这仅取决于股息和除数的类型。

    double v = 1 / 2; // v == 0.0 (!!!)

您还应该注意 double也是一个有限精度的数字。

    System.out.println(.2D + .7D - .9D); // prints "-1.1102230246251565E-16"

但是我的代码呢?

那么现在,让我们关注一下您的代码发生了什么:

  timeTaken = stopTime - startTime;
timeInSecs = ((timeTaken/1000));
speed = 45/timeInSecs;

很可能发生的事情是 timeTaken被声明为 long .因此timeTaken/1000结果是整数除法。如果timeTaken < 1000 ,除法结果为0 .

此时,timeInSecs 是否无关紧要是 doublefloat ,因为已经进行了整数除法。这意味着 timeInSecs要么是 00.0 ,取决于它的类型。

不过,根据您得到的错误,可以确定 timeInSecs很可能是整数类型。否则,45/timeInSecs将导致浮点除法,结果为 Infinity (一个特殊的 double 值)而不是抛出 ArithmeticException .

那么我们该如何解决这个问题?

我们可以通过如下声明变量来解决这个问题:

long timeTaken;
double timeInSecs;
double speed;

然后执行如下计算(注意 1000 现在是一个 double 值)。

timeTaken = stopTime - startTime;
timeInSecs = timeTaken/1000D;
speed = 45D/timeInSecs; // D is not necessary here, but it's good for clarity

另见

关于java - 算术异常Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com