0

我正在尝试为后缀计算器编写中缀。我正在读取包含以下内容的文件:

(4>3)+(3=4)+2

当我运行我的代码时,我应该得到一个包含输入的后缀表示法的字符串,但是我什么也没得到。我的代码似乎没有达到最终的打印声明。同样,当我修改代码以使其至少打印时(尽管符号不正确),它只打印数字而不是运算符(+、-、& 等)。我无法弄清楚为什么会这样!我在下面的代码中标记了打印语句的位置:

public static void main(String[] args) {

        readMathFile();
}

static String PF = "";

    public static void postfix(char c, myStack s, myQueue q) {
        if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' ||
                c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
            String cc = Character.toString(c);
            PF.concat(cc);
        } else if(c == '!' || c == '*' || c == '/' || c == '+' || c == '-' || 
                c == '<' || c == '>' || c == '=' || c == '&' || c == '|') {
            if(s.isEmpty())
                s.push(c);
            else {
                char top = s.peek();
                while ((precedence(top) > precedence(c)) && !s.isEmpty()) {
                    String cd = Character.toString(s.pop());
                    PF.concat(cd);
                }
                s.push(c);
            }
        }


    }


    public static myStack s;
    public static myQueue q;
    public static int i = 1;

    // the file reading code was borrowed from:
    // http://www.java2s.com/Code/Java/File-Input-Output/Readfilecharacterbycharacter.htm
    public static void readMathFile() {
        s = new myStack();
        q = new myQueue();
        File file = new File("test.txt");
        if (!file.exists()) {
            System.out.println(file + " does not exist.");
            return;
        }
        if (!(file.isFile() && file.canRead())) {
            System.out.println(file.getName() + " cannot be read from.");
            return;
        }
        try {
            FileInputStream fis = new FileInputStream(file);
            char current;
            // in this while loop is where all of the reading happens
            while (fis.available() > 0) {
                current = (char) fis.read();
                //readMath(current, s, q);
                postfix(current, s, q);
            }
            if(fis.available() == 0) {
                char x = s.pop();
                while(!s.isEmpty()) {
                    //q.enqueue(s.pop());
                    String ce = Character.toString(s.pop());
                    PF.concat(ce);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("\n\n"+PF); // <----CODE NEVER REACHES THIS POINT! (and when i modify so it does, it will not print the operators!)
    }
4

0 回答 0