我试图通过创建一个简单的计算器来处理涉及括号的算术表达式来巩固我对堆栈和运算符的理解。我觉得我的代码应该可以工作,但它肯定没有给我正确的输出。
即使我有一个方法来评估每个表达式,当我尝试返回数字堆栈时,它也不会打印出任何评估方法,而只会打印出用户输入的所有数字。我还想处理输入中的问题,例如运算符不匹配或缺少括号。
我尝试使用 9 * 5 或类似 (7 * 6) + (9 - 4) 之类的简单表达式来运行代码,但它只返回最后一个 double 。
到目前为止,这是我的代码:
主要方法
import java.util.Stack;
import javax.swing.JOptionPane;
public class Calculator {
// instance variables
private Stack < Double > nums;
private Stack < String > ops;
String list;
// constructor
public Calculator()
{
nums = new Stack < Double > ();
ops = new Stack < String > ();
}
// methods
public static boolean isDouble(String str) {
try {
Double.parseDouble(str);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
public static boolean isValidOp(String str) {
return (str == "(" || str == ")" || str == "^" || str == "*" || str == "/" || str == "+" || str == "-");
}
public int prec(String str) {
if (str == "(" || str == ")")
return 4;
if (str == "^")
return 3;
if (str == "*" || str == "/")
return 2;
if (str == "+" || str == "-")
return 1;
else
return -1;
}
public double applyOperator(double left, String op, double right) {
if (op == "+") {
return (left + right);
}
if (op == "-") {
return (left - right);
}
if (op == "*") {
return (left * right);
}
if (op == "/") {
return (left / right);
}
if (op == "^") {
return Math.pow(left, right);
} else {
throw new IllegalArgumentException("Not a valid operator");
}
}
public String evaluate(String str)
{
String [] tokens = str.split(" ");
for (int i = 0; i < tokens.length; i++)
{
if (isDouble(tokens [i]) == true)
{
nums.push(Double.parseDouble(tokens [i]));
}
if (tokens [i] == "(")
{
ops.push(tokens [i]);
}
if (tokens [i] == ")")
{
String op1 = ops.pop();
double num1 = nums.pop();
double num2 = nums.pop();
double result = applyOperator(num1,op1,num2);
nums.add(result);
}
if (tokens [i] == "+" || tokens [i] == "-" || tokens [i] == "*" || tokens [i] == "/" || tokens [i] == "^")
{
if(ops.isEmpty())
{
ops.push(tokens [i]);
}
else if (prec(tokens [i]) > prec(ops.peek()))
{
ops.push(tokens [i]);
}
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
String ac1 = ops.pop();
double res1 = nums.pop();
double res2 = nums.pop();
double outcome = applyOperator(res1,ac1,res2);
nums.add(outcome);
}
}
}
while(!ops.isEmpty() && nums.size() > 1)
{
String ab = ops.pop();
double bb = nums.pop();
double cb = nums.pop();
double clac = applyOperator(bb,ab,cb);
nums.add(clac);
}
String fix = nums.pop().toString();
return fix;
}
}
测试人员:
import javax.swing.JOptionPane;
public class AppforCalc {
public static void main(String [] args)
{
Calculator calc = new Calculator();
String reply = "yes";
String instructions = "Enter a mathematical expression. Separate everything with spaces";
while(reply.equalsIgnoreCase("yes"))
{
String expression = JOptionPane.showInputDialog(instructions);
String ans = calc.evaluate(expression);
reply = JOptionPane.showInputDialog("The solution is " + ans + "Try again?");
}
}
}
最佳答案
算法失败的主要原因是在尝试检查 String
相等性时使用了 ==
。
在 Java 中,==
是一个 boolean 运算符,它对所有操作数的行为相同,并检查操作数的值是否相等。这意味着原语会像人们预期的那样被检查,但是作为对象的字符串将导致比较两个字符串的内存引用,只有当两个字符串实际上是相同的字符串时才会结果为真。这意味着必须使用 equals
方法来完成字符串相等性检查。
计算器的行为存在更多问题(算法问题),但在处理字符串相等性检查后这些问题将更容易识别和修复。必须解决的问题的一个示例是:
while(!ops.isEmpty() && nums.size() > 1)
{
String ab = ops.pop();
double bb = nums.pop();
double cb = nums.pop();
double clac = applyOperator(bb,ab,cb);
nums.add(clac);
}
操作数(bb
和 cb
)从堆栈中弹出,因此它们以相反的顺序到达(解析时,cb
是在 bb
之前压入堆栈)。这意味着 cb
是左侧操作数,bb
是右侧操作数 -> double clac = applyOperator(cb,ab,bb);
的应该对 applyOperand
方法的所有用法进行相同的重构。
另一个问题如下:
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
String ac1 = ops.pop();
double res1 = nums.pop();
double res2 = nums.pop();
double outcome = applyOperator(res1,ac1,res2);
nums.add(outcome);
}
进行了内部评估,但评估的触发是发现出现率较低的操作数。计算后应将操作数压入操作堆栈:
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
...
...
nums.add(outcome); // I highly suggest refactoring this to nums.push due to readability considerations
ops.push(tokens[i]);
}
引用资料:
关于java - 创建一个 "calculator"来评估 Java 中的算术表达式 - 代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756663/