代码拉取完成,页面将自动刷新
package Project.Arithmetic;
import java.util.StringTokenizer;
import java.util.Stack;
public class Calculator
{
private final char ADD = '+';
private final char SUBTRACT = '-';
private final char MULTIPLY = '*';
private final char DIVIDE = '÷';
private Stack<String> stack;
private RationalNumber r, r1, r2;
public boolean isOperator (String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("÷") );
}
public String evalSingleOp (char operation, RationalNumber op1, RationalNumber op2)
{
RationalNumber result = new RationalNumber(0,1);
switch (operation)
{
case ADD:
result = r1.add(r2);
break;
case SUBTRACT:
result = r1.subtract(r2);
break;
case MULTIPLY:
result = r1.multiply(r2);
break;
case DIVIDE:
result = r1.divide(r2);
}
return result.toString();
}
public RationalNumber tranIntoRationalNum (String s){
String token1, token2;
StringTokenizer tokenizer1 = new StringTokenizer(s, "/");// Divide the operation number to "/" as a mark
token1 = tokenizer1.nextToken();
if (tokenizer1.hasMoreTokens()) {// If there are second elements, token1 is placed in the position of the molecule,
// and token2 is placed in the denominator.
token2 = tokenizer1.nextToken();
r = new RationalNumber(Integer.parseInt(token1), Integer.parseInt(token2));
}
else {// If there are no second elements, the token1 will be placed in the molecular position and the denominator will be fixed to 1.
r = new RationalNumber(Integer.parseInt(token1),1);
}
return r;
}
public Calculator() {
stack = new Stack<String>();
}
public String evaluate (String expr)
{
String op1, op2, result = null;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
// If it is the operator, call isOperator
if (isOperator(token))
{
// From the stack, the number of operands is popped up to 2 and converted to RationalNumber type.
op2 = stack.pop();
r2 = tranIntoRationalNum(op2);
// From the stack, the number of operands is popped up to 1 and converted to RationalNumber type.
op1 = stack.pop();
r1 = tranIntoRationalNum(op1);
// EvalSingleOp is calculated by calling the result according to the operator and two operands.
result = evalSingleOp(token.toCharArray()[0], r1, r2);
// Compute the result and enter the stack
result = stack.push(result);
}
else // If it is an operand enter the stack
stack.push(token);
}
return result;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。