Java 如何将变量(字母)输入计算器类函数
这是密码 我有一个计算器类,现在它只计算数字,但我试图让它计算一个变量,并将变量的值设置为一个特定的数字,即Java 如何将变量(字母)输入计算器类函数,java,Java,这是密码 我有一个计算器类,现在它只计算数字,但我试图让它计算一个变量,并将变量的值设置为一个特定的数字,即5 对不起,我不清楚。当我运行这个计算器,输入1+1,它会给我2作为答案。但我希望能够包括一个变量,例如3*x^2或3*y^2。变量的值为5。现在这个代码无法做到这一点 public class Calculator { // Allowable mathematical operators static final String operators = "+-*/%()
5
对不起,我不清楚。当我运行这个计算器,输入1+1,它会给我2作为答案。但我希望能够包括一个变量,例如3*x^2或3*y^2。变量的值为5。现在这个代码无法做到这一点
public class Calculator {
// Allowable mathematical operators
static final String operators = "+-*/%()^!";
private String strPostfix;
private String strInfix;
private char chrVariable;
private int intError;
/**
* Default constructor. Sets all local values to default values
*/
public Calculator() {
setEquation("");
}
/**
* Sets a new equation.
* @param equation The new equation.
* @remarks Note that this also resets all values stored same as creating a new object
*/
public void setEquation(String equation)
{
// Remove any spaces, as they aren't necessary
strInfix = equation.replace(" ", "").trim();
strPostfix = "";
chrVariable = '\0';
intError = -2;
}
/**
* Gets the character location of the error found. -1 means no error found.
* @return An integer specifying the location of the error.
*/
public int get_ErrorLocation()
{
return intError + 1;
}
/**
* Gets the operators being used
* @return The operators
*/
public String get_Operators()
{
return operators;
}
/**
* Gets the post fix equation stored in memory for this object
* @return A post fix equation stored in a string
*/
public String get_PostFix()
{
return strPostfix;
}
/**
* Gets the variable that is in the equation. '~' means no variable found.
* @return The variable being used in the equation.
*/
public char get_Variable()
{
return chrVariable;
}
/**
* Solves the equation stored in memory for this instance, and stores it in memory
* @return A solution to a pre-existing equation
* @throws NoEquationException Occurs when attempting to solve an equation that doesn't exist
* @throws DivisionByZeroException Thrown when attempting to divide by zero
* @throws InvalidEquationException Occurs if an equation is invalid for an undefined reason
* @throws ExistingVariableException Occurs when attempting to use two variables
* @throws InvalidCharacterException Occurs when an invalid character is entered
*/
public double Solve() throws NoEquationException, DivisionByZeroException, InvalidEquationException, InvalidCharacterException, ExistingVariableException
{
strPostfix = PostFix().trim();
System.out.println(strPostfix);
return SolvePost();
}
/**
* Determines the precendence of a give mathematical operator
* @param value The mathematical operator
* @return The precendence of the operator
*/
private short precedence(char value) {
switch (value) {
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '!':
return 3;
case '^':
return 4;
default:
return -1;
}
}
/**
* Turns an infix equation into post-fix
* @return The post-fix equivalent of the equation
* @throws InvalidEquationException When an invalid equation is given
* @throws ExistingVariableException Occurs when attempting to use two variables
* @throws InvalidCharacterException Occurs when an invalid character is entered
* @throws NoEquationException Occurs when attempting to solve an equation that doesn't exist
*/
private String PostFix() throws InvalidEquationException, InvalidCharacterException, ExistingVariableException {
// Backup the equation
String infix = strInfix;
String postfix = "";
char current;
char chrVariable;
Stack<Character> stack = new Stack<Character>();
boolean hasDec = false;
// For every character in the string
for ( int idx = 0; idx < infix.length(); ++idx ) {
current = infix.charAt(idx);
// If it is a digit or letter , just add it to postfix
if ( Character.isDigit(current) ) {
postfix += current;
// If it is a decimal, make sure there is only one per number
}else if (Character.isLetter(current))
postfix+=current;
else if( current == '.' ) {
if (!hasDec)
postfix += String.valueOf(current);
else
throw new InvalidEquationException();
hasDec = true;
// Otherwise, its an operator
}
else {
postfix += " ";
hasDec = false;
char peek;
// If there's an opening brace, just push it to the stack
if ( current == '(' )
stack.push(current);
// If its a closing brace, find pop until you find the opening one
else if ( current == ')' ) {
while ( !stack.isEmpty() && stack.peek() != '(' ) {
postfix += stack.pop() + " ";
}
// If the stack is empty, '(' was not found, error
if (stack.isEmpty()) { throw new InvalidEquationException('('); }
// Remove the '(' from the list
stack.pop();
} else {
if ( current == '-' && ( idx == 0 || operators.contains(String.valueOf(infix.charAt(idx - 1))))) {
postfix += current;
} else {
short prec = precedence(current);
if ( prec == -1 ) {
intError = idx;
throw new InvalidCharacterException();
}
// Pop off everything that has greater or equal precedence
if ( !stack.isEmpty() ) {
peek = stack.peek();
while ( precedence(current) <= precedence(peek) ) {
postfix += stack.pop() + " ";
if ( !stack.isEmpty() )
peek = stack.peek();
else
break;
}
}
// Now add the current onto the stack
stack.push(current);
}
}
}
}
// Finally, empty out the stack
while ( !stack.isEmpty() ) {
postfix += " " + stack.pop();
}
postfix = postfix.trim();
while ( postfix.contains(" ") ) {
postfix = postfix.replaceAll(" ", " ");
}
return postfix;
}
/**
* Solves the post-fix equation
* @return The solution to the equation
* @throws NoEquationException Thrown when PostFix equation not set
* @throws DivisionByZeroException Thrown when attempting to divide by zero
* @throws InvalidEquationException When an invalid equation is given
*/
private double SolvePost() throws NoEquationException, DivisionByZeroException, InvalidEquationException {
// Make sure there is an equation to solve
if ( strPostfix.trim().isEmpty() )
throw new NoEquationException();
Stack<Double> stack = new Stack<Double>();
String tokens[] = strPostfix.split(" ");
for ( String current : tokens ) {
try {
// If its a number, just push it
stack.push(Double.parseDouble(current));
} catch (Exception e) {
// If its not an operator, there's a problem
if ( current.length() > 1 || !operators.contains(current) )
throw new InvalidEquationException();
// there must be two operands, otherwise there's a problem
double first = 0, second = 0;
try {
second = stack.pop();
if ( current.charAt(0) != '!' )
first = stack.pop();
} catch (Exception ex) {
throw new InvalidEquationException();
}
// Do the appropriate math
switch ( current.charAt(0) ) {
case '+':
stack.push(first + second);
break;
case '-':
stack.push(first - second);
break;
case '*':
stack.push(first * second);
break;
case '/':
// Make sure its not division by zero
if (second == 0) { throw new DivisionByZeroException(); }
stack.push(first / second);
break;
case '%':
stack.push(first % second);
break;
case '^':
stack.push(Math.pow(first, second));
break;
case '!':
if ( (int)second != second || second < 0 )
throw new InvalidEquationException();
int result = 1;
for ( int i = 2; i <= second; ++i )
result *= i;
stack.push((double)result);
break;
default:
// Anything else isn't valid
throw new InvalidEquationException();
}
}
}
return stack.pop();
}
}
公共类计算器{
//允许的数学运算符
静态最终字符串运算符=“+-*/%()^!”;
私有字符串strPostfix;
私有字符串strInfix;
私有变量;
私人int Interor;
/**
*默认构造函数。将所有本地值设置为默认值
*/
公共计算器(){
方程组(“”);
}
/**
*设定一个新的方程式。
*@param方程-新方程。
*@备注注意,这也会重置与创建新对象相同的所有存储值
*/
公共方程(弦方程)
{
//删除所有空格,因为它们不是必需的
strInfix=公式。替换(“,”).trim();
strPostfix=“”;
chr变量='\0';
interor=-2;
}
/**
*获取找到的错误的字符位置。-1表示未找到错误。
*@返回指定错误位置的整数。
*/
public int get_ErrorLocation()
{
返回interor+1;
}
/**
*获取正在使用的运算符
*@返回操作员
*/
公共字符串get_运算符()
{
返回操作员;
}
/**
*获取存储在此对象的内存中的修复后等式
*@返回存储在字符串中的修复后等式
*/
公共字符串get_PostFix()
{
返回strPostfix;
}
/**
*获取表达式中的变量。“~”表示未找到变量。
*@返回方程式中使用的变量。
*/
公共字符get_变量()
{
返回变量;
}
/**
*为该实例求解存储在内存中的方程式,并将其存储在内存中
*@返回预先存在的方程的解
*@NoEquationException在尝试求解不存在的方程时发生
*@throws divisionbyzero尝试除以零时引发异常
*如果方程式因未定义的原因无效,则会发生@throws InvalidEquationException
*@throws ExistingVariableException在尝试使用两个变量时发生
*@throws InvalidCharacterException在输入无效字符时发生
*/
public double Solve()抛出NoEquationException、DivisionByZeroException、InvalidQuationException、InvalidCharacterException、ExistingVariableException
{
strPostfix=PostFix().trim();
System.out.println(strPostfix);
返回后();
}
/**
*确定给定数学运算符的进阶
*@param value是一个数学运算符
*@返回运算符的前置值
*/
专用短优先级(字符值){
开关(值){
格“+”:
案例'-':
返回1;
案例“*”:
案例“/”:
案例“%”:
返回2;
案例“!”:
返回3;
案例‘^’:
返回4;
违约:
返回-1;
}
}
/**
*将中缀公式转换为后修复
*@返回等式的后修复等价项
*@在给出无效方程式时抛出InvalidEquationException
*@throws ExistingVariableException在尝试使用两个变量时发生
*@throws InvalidCharacterException在输入无效字符时发生
*@NoEquationException在尝试求解不存在的方程时发生
*/
私有字符串后缀()引发InvalidQuationException、InvalidCharacterException、ExistingVariableException{
//支持这个等式
字符串中缀=strInfix;
字符串后缀=”;
炭流;
char变量;
堆栈=新堆栈();
布尔hasDec=false;
//对于字符串中的每个字符
对于(int idx=0;idx