【发布时间】:2012-02-05 22:06:33
【问题描述】:
我目前正在使用 Java 计算器程序,一切似乎都正常工作,但我想要更多功能。
现在用户可以输入一个数学表达式,程序会解决它。但是,我希望程序能够为 x、y 或 z 等变量分配数值。
示例输入/输出可以是:
输入表达式:x=10/5
=> 2输入表达式:x
=> 2
public class Calculator
{
String expstring;
int cursor;
double x;
double y;
double z;
public Calculator()
{
expstring = null;
x = 0;
y = 0;
z = 0;
}
public Calculator(String instring)
{
expstring = instring;
cursor = 0;
}
public void setExpression(String estring)
{
expstring = estring;
cursor = 0;
}
public float evalExp()
{
if (expstring == null)
{
System.err.println("There is no expression to evaluate.");
System.err.println("Call setExpression() before calling getResult().");
return 0;
}
cursor = 0;
float result = evalTerm();
while (nextOperator('+') || nextOperator('-'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '+')
result = result + term;
if (operator == '-')
result -= term;
else
System.err.println("Invalid operator: " + operator);
}
return result;
}
private float evalTerm()
{
float result = getOperand();
while (nextOperator('*') || nextOperator('/'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '*')
result = result * term;
if (operator == '/')
result /= term;
else
break;
}
return result;
}
private float getOperand()
{
if (cursor >= expstring.length())
return 0;
String opstring = "";
char nextchar = expstring.charAt(cursor);
if (nextchar == '-')
{
opstring = opstring + '-';
cursor++;
nextchar = expstring.charAt(cursor);
}
/** if (nextchar == 'x')
{
x =
}
*/
while (cursor < expstring.length() && !isOperator(nextchar))
{
opstring = opstring + nextchar;
cursor++;
if (cursor < expstring.length())
nextchar = expstring.charAt(cursor);
}
return Float.parseFloat(opstring);
}
private char getOperator()
{
char operator = expstring.charAt(cursor);
cursor++;
return operator;
}
private boolean nextOperator(char op)
{
if (cursor < expstring.length() && expstring.charAt(cursor) == op)
return true;
else
return false;
}
private boolean isOperator(char c)
{
String opset = "+*-/";
return (opset.indexOf(c) >= 0);
}
}
这是我到目前为止的工作,但我不确定如何将其实现到代码中...变量和赋值的处理可以作为特殊情况嵌入到上面的逻辑结构中,或者可以完成在评估表达式之前/之后的单独逻辑中。您的计算器类将需要一个字段来存储每个变量(x、y 和 z)的值。在赋值中,第一个操作数是变量名,第一个运算符是 =。 = 右边的表达式的值必须被计算,然后该值可以存储在与变量对应的字段中。如果 x、y 或 z 出现在 = 右侧的表达式中,则可以在相应字段中找到其当前值。变量可以在获取下一个操作数的代码中替换为它们的值,或者变量值可以在表达式被计算之前插入到单独的传递中。
任何帮助、煽动性链接或建议都会很棒!
我是编程领域的新手,想学习。
【问题讨论】:
标签: java parsing variables calculator