我正在尝试在Android中制作一个基本的计算器,并且我正在使用 Infix到Postfix 转换我正在从 EditText 获取我的输入并将其转换为一个字符串,并在评估方法中传递它.....但当我运行它并按等于按钮来评估我的结果我的应用程序崩溃下面是代码和logcat。
public class Evaluate {
String[] evalStack = new String[100];
String[] stackPostfix = new String[100];
char[] operatorStack = new char[100];
int top,j,k,i,top_operator_stack;
String number="";
public void InfixToPostfix(String s){
k=0;
top=s.length();
top_operator_stack=0;
operatorStack[top_operator_stack]='(';
for(i=0;i<top;i++)
{
char extract = s.charAt(i);
if(extract!='+'&&extract!='-'&&extract!='*'&&extract!='/'&&extract!='^'&&extract!='('&&extract!=')')
{
number=number+extract;
}else if(extract=='+'||extract=='-'||extract=='*'||extract=='/'||extract=='^')
{
if(number!="")
{
stackPostfix[k++]=number;
number="";
}
operatorStack[++top_operator_stack]=extract;
for(j=top_operator_stack-1;operatorStack[j]!='(';j--)
{
int currentOperatorPriority,previousOperatorPriority;
currentOperatorPriority = returnPriority(operatorStack[i]);
previousOperatorPriority = returnPriority(operatorStack[j]);
if(previousOperatorPriority>=currentOperatorPriority)
{
stackPostfix[k++]=""+operatorStack[j];
operatorStack[j]=operatorStack[j+1];
top_operator_stack--;
}
}
}else if(extract=='('){
if(number!="")
{
stackPostfix[k++]=number;
number="";
}
operatorStack[++top_operator_stack] = '(';
}else if(extract==')'){
if(number!="")
{
stackPostfix[k++]=number;
number="";
}
while(operatorStack[top_operator_stack]!='(')
{
stackPostfix[k++] = "" + operatorStack[top_operator_stack--];
}
top_operator_stack--;
}
}
}
private static int returnPriority(char ch){
switch(ch){
case '+':return 1;
case '-':return 1;
case '/':return 2;
case '*':return 2;
case '^':return 3;
}
return 0;
}
public String EvaluatePostfix(){
top=0;
for(int i =0;stackPostfix[i]!=")";i++)
{
if(stackPostfix[i]!="+"&&stackPostfix[i]!="-"&&stackPostfix[i]!="*"&&stackPostfix[i]!="/"&&stackPostfix[i]!="^")
{
evalStack[top++]=stackPostfix[i];
}else{
String sym = stackPostfix[i];
double top_element = Double.parseDouble(evalStack[top]);
double next_top_element = Double.parseDouble(evalStack[top-1]);
switch(sym){
case "+" :evalStack[top--]=""+(next_top_element+top_element);
break;
case "-" :evalStack[top--]=""+(next_top_element-top_element);
break;
case "/" :evalStack[top--]=""+(next_top_element/top_element);
break;
case "*" :evalStack[top--]=""+(next_top_element*top_element);
break;
case "^" :evalStack[top--]=""+(Math.pow(next_top_element, top_element));
break;
}
}
}
return evalStack[0];
}
![LogCat When App Crashes][1]}