检查Java中的double是否是无限的
我正在为这个家庭作业制作一个简单的计算器,Java在除以0时返回“Infinity”。
当我得到无限时,我需要显示一些错误信息。 问题是我不知道该怎么办
double result; result = 4/0; //if result == infinity then some message - need help with this
你可以使用Double.isInfinite(双)
这是双文档
上面的代码产生
ArithmeticException: / by zero
您可以在try / catch块中捕获此exception。
请查看它是否等于Double.POSITIVE_INFINITY
double result; result = 4.0 / 0.0;
Double
类中有两个无穷大字段: POSITIVE_INFINITY
和NEGATIVE_INFINITY
,您可以检查它们。
请注意,整数除以零将抛出ArithmeticException
因此您的行必须是4.0/0
4/0.0
或4.0/0.0
因为4和0是整数,因此导致整数数学运算。
JacekKwiecień尝试此代码
double result; try{ result=4.0/0.0; }catch(ArithmeticException e){ System.out.println("Math error "+ e.getMessage()) }
`
恢复一个超级老问题,因为它出现在我的Java类中。 所以我确定你像他们所建议的那样尝试了try / catch,但你发现,和我一样,它不适用于Double
。 带有ArithmeticException的try / catch在Double
或Float
上不起作用,因为它们返回“Infinity”而不是返回exception。 (注意,因为它不是一个答案,因此给了myold“回答”)。
在这里拼凑了几个不同的问题/答案,我提出了以下试验。
public class trial { public static void main(String[] args) { double a; try { a = 4/0; System.out.println(" The answer is " +a); } catch(ArithmeticException e) { System.out.println(" You can't divide by zero. Please try again."); } } }
上面的代码应该给你结果“答案是无穷大”。 至少它对我有用,因为它是double
。
使用int
,它不需要下面的if
语句,因为它会引发exception。 但由于它是一个Double
,下面的if
语句将导致它抛出一个exception, catch
将…好吧……捕获。
public class trial { public static void main(String[] args) { double a; try { a = 4/0; // if statement to throw an AtithmeticException if ans equals infinity if(a == Double.POSITIVE_INFINITY){ throw new ArithmeticException(); } else{ System.out.println(" The answer is " +a); } } catch(ArithmeticException e) { System.out.println(" You can't divide by zero. Please try again."); } } }
这种错误称为exception。 您可以使用try-catch块来捕获此exception。
try{ result = 4/0; } catch(ArithmeticException e){ System.out.println("You divided by zero"); }
你可以在这里阅读有关exception处理