【发布时间】:2018-08-07 11:29:27
【问题描述】:
我创建了一个 Java 计算器,但是我需要添加代码,以便在数字除以零时将结果设置为零。其他一切都在工作,我只是不知道在哪里添加此语句。
代码如下:
public class Calculator
{
// Declaration of a long variable to hold the stored result
private long theResult = 0;
private long zero = 0;
// Evaluate an arithmetic operation on the stored result
// E.g evaluate( '+', 9) would add 9 to the stored result
// evaluate( '/', 3) would divide the stored result by 3
// actions are '+'. '-', '*', '/'
// Note: if the operation is
// evaluate( '/', 0 ) the theResult returned must be 0
// (Not mathematically correct)
// You will need to do a special check to ensure this
/**
* perform the operation
* theResult = theResult 'action' number
* @param action An arithmetic operation + - * /
* @param number A whole number
*/
public void evaluate( char action, long number)
{
if (action == '+'){
theResult += number;
}
else if (action == '-'){
theResult -= number;
}
else if (action == '*'){
theResult *= number;
}
else if (action == '/'){
theResult /= number;
}
}
/**
* Return the long calculated value
* @return The calculated value
*/
public long getValue()
{
return theResult;
}
/**
* Set the stored result to be number
* @param number to set result to.
*/
public void setValue( long number )
{
this.theResult = number;
}
/**
* Set the stored result to be 0
*/
public void reset()
{
if ( theResult != 0) theResult = 0;
// im not sure this is correct too
}
}
【问题讨论】:
-
如果没有您的实际代码,我猜想在实际除法之前是
if。检查除数是否为0。如果是,则结果为0。否则,进行除法。 -
编辑后,在实际分割完成之前,它会在块
if (action == '/') {...}中。 -
我将如何检查是否有人在这里除以零
-
检查输入或捕获异常(ArithmeticException)
标签: java division arithmetic-expressions