Java零除计算器
我已经创建了一个Java计算器,但是我需要添加代码,当数字除以零时,我将结果设置为零。其他一切都在起作用,我只是不知道该在哪里添加这句话 代码如下:Java零除计算器,java,division,arithmetic-expressions,Java,Division,Arithmetic Expressions,我已经创建了一个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 operatio
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语句,如下所示:
else if (action == '/'){
if (number == 0){ //this is the start of the nested if statement
theResult = 0; //alternatively, you can just type "continue;" on this line since it's 0 by default.
}
else {
theResult /= number;
}
}
有两种方法可以做到这一点。第一种可能是:
else if (action == '/') {
if( number == 0 )
theResult = 0;
else
theResult /= number;
}
另一个选项假设您已经了解了异常:
else if (action == '/') {
try {
theResult /= number;
}
catch( ArithmeticException ae ) {
// possibly print the exception
theResult = 0;
}
}
如果没有实际的代码,我会在实际除法之前猜测if。检查除数是否为0。如果是,则结果为0。否则,进行除法。编辑后,如果action='/'{…},则它将位于块中,在实际除法完成之前,我如何检查是否有人在这里被零除法,然后检查输入或捕获异常算术异常我没有了解异常,但这是错误消息中显示的内容,因此尝试研究它,谢谢,这也是有意义的