堆栈实现问题/不打印某些字符

时间:2013-02-23 15:30:01

标签: java postfix-notation

我正在尝试写一个中缀到后缀计算器。我正在阅读包含以下内容的文件:

  

(4→3)+(3 = 4)2

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

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!)
    }

0 个答案:

没有答案