有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

共 (0) 个答案