0
我似乎無法得到嘗試塊內部的堆棧,我的意思是通過在try塊內使用堆棧來獲得一位數的計算器。 try塊的內部是給我的EmptyStackExceptionjava中綴計算器
import java.util.EmptyStackException;
import java.util.*;
public class Infix
{
public static void main(String[] args){
System.out.println(evaluateInfix("1*2*3"));
}
public static double evaluateInfix(String infix)
{
try
{
Stack<Character> valueStack = new Stack<Character>();
Stack<Character> operatorStack = new Stack<Character>();
double result;
for(char ch: infix.toCharArray()){
if(ch >= 0 && ch <= 9){
valueStack.push(ch);
} else if(ch == '('){
operatorStack.push(ch);
} else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '='){
if(operatorStack.isEmpty()){
operatorStack.push(ch);
} else if(precedence(ch) > precedence(operatorStack.peek())){
operatorStack.push(ch);
} else {
while(!operatorStack.isEmpty() && precedence(ch) <= precedence(operatorStack.peek())){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
operatorStack.push(ch);
}
} else if(ch == ')'){
while(operatorStack.peek() != '('){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
operatorStack.pop();
}
}
while(!operatorStack.isEmpty()){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
result = valueStack.peek();
System.out.println(result);
/* **********
Task 3
complete this section to calculate the infix expression
*/
} //end try
catch (EmptyStackException e)
{
/* **********
Task 3
complete this to return Double.NaN
*/
}
catch (ArithmeticException e)
{
/* **********
Task 3
complete this to return Double.NEGATIVE_INFINITY
*/
}
return 3.0;
} // end evaluateInfix
private static int precedence(char operator)
{
switch(operator){
case '(': case ')': return 0;
case '+': case '-': return 1;
case '*': case '/': case '%': return 2;
case '^': return 3;
case '=': return 4;
}
return -1;
}
private static double valueOf(char variable)
{
switch (variable)
{
case '1': return 1.0;
case '2': return 2.0;
case '3': return 3.0;
case '4': return 4.0;
case '5': return 5.0;
case '6': return 6.0;
case '7': return 7.0;
case '8': return 8.0;
case '9': return 9.0;
case '0': return 0.0;
} // end switch
return 0;
} // end valueOf
private static Double compute(Double operandOne, Double operandTwo, char operator)
{
if(operator == '+'){
return operandOne + operandTwo;
} else if(operator == '-'){
return operandOne - operandTwo;
} else if(operator == '*'){
return operandOne * operandTwo;
} else if(operator == '/'){
return operandOne/operandTwo;
} else if(operator == '%'){
return operandOne % operandTwo;
} else if(operator == '^'){
return Math.pow(operandOne, operandTwo);
} else {
return null;
}
} // end compute
} // end Infix
的try塊是方法evaluateInfix如果我要去掉括號中的代碼將無法編譯 – 2013-02-11 12:04:16
遺憾清除一些東西 – 2013-02-11 12:07:32
當我加入了缺失的方法,我不小心刪除的方法,由於 – 2013-02-11 12:09:45