0

私は後置ソリューションを書いています。なぜ機能しないのかわかりません。出力に -1 が表示され続けます。誰か助けてくれませんか?ランナーとランナーと実際の後置クラスを含めます。

import java.util.Stack;
import java.util.Scanner;
import static java.lang.System.*;

public class PostFixRunner
{
public static void main ( String[] args )
{
    PostFix test = new PostFix("2 7 + 1 2 + +");
    System.out.println(test.solve());

    test.setExpression("1 2 3 4 + + +");
    System.out.println(test.solve());

    test.setExpression("9 3 * 8 / 4 +");
    System.out.println(test.solve());

    test.setExpression("3 3 + 7 * 9 2 / +");
    System.out.println(test.solve());


    test.setExpression("9 3 / 2 * 7 9 * + 4 -");
    System.out.println(test.solve());


    test.setExpression("5 5 + 2 * 4 / 9 +");
    System.out.println(test.solve());

    }
}

この...

import java.util.Stack;
import java.util.Scanner;
import static java.lang.System.*;

public class PostFix
{
private Stack<Integer> stack;
private String theExp;

public PostFix()
{

}

public PostFix(String exp)
{
    theExp = exp;
    stack = new Stack<Integer>();
}

public void setExpression(String exp)
{
    theExp= exp;
    while (!stack.isEmpty()){
        stack.pop();
    }
}

public int  calc(int two, int one, char current)
{
    int output;
    switch(current){
    case '*':
        output=one*two;
        break;
    case '/':
        output=one/two;
        break;
    case '+':
        output=one+two;
        break;
    case '-':
        output=one-two;
        break;
    default:
        output=0;
    }
    return output;
}

public int solve()
{
    for (int i=0; i<theExp.length(); i++){
        char current = theExp.charAt(i);
        int currentInt = (int)Character.digit(current, 10);
        if (current!='*'||current!='/'||current!='+'||current!='-')
            stack.push(currentInt);
        else
            stack.push(calc(stack.pop(), stack.pop(), current));
    }
    return stack.pop();
}

public String toString(){
    return stack.toString();
    }
}
4

0 に答える 0