TXT文件中的Java堆栈评估

时间:2018-10-17 02:35:03

标签: java stack equation evaluation

在此作业中,我需要读取一个.txt文件并确定表达式是正确的还是“平衡的”。第一个问题我是正确的,但第二个问题我的输出却比我想要的多。这是#2的问题:

  

编写一个基于堆栈的算法,该算法评估后置表达式。您的程序需要从名为“ problem2.txt”的文件中读取其输入。该文件每行包含一个表达式。       对于每个表达式,将其值输出到标准输出。如果表达式格式错误,请打印“格式错误”。

问题2.txt如下:

3  2  +  5  6  8  2  /  +  +  *  1  + 
8 * 2  3 + + -  9 1 +
1  4  +  9  4  -  *  2  *
// For my output I need to get:
76
Ill-formed
50

// With my code I am getting:
76
Ill-formatted
Ill-formatted
Ill-formatted
10
50
// and I’m not sure why I’m getting extra ill-formatted and a 10 in there

下面是我的代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
import java.util.EmptyStackException;

public class Eval {

    public static void main(String args[]) throws IOException {
    //driver
        try (BufferedReader filereader = new BufferedReader(new FileReader("Problem1.txt"))) {
            while (true) {
                String line = filereader.readLine();
                if (line == null) {
                   break;
                }

                System.out.println(balancedP(line));
            }
        }
        System.out.println("\n");
        try (BufferedReader filereader2 = new BufferedReader(new FileReader("Problem2.txt"))) {
            while (true) {
                String line = filereader2.readLine();
                if (line == null) {
                   break;
                }

                System.out.println(evaluatePostfix(line));
            }
        }
    }


    public static boolean balancedP (String s) {
        Stack<Character> stackEval  = new Stack<Character>();

        for(int i = 0; i < s.length(); i++) {

            char token = s.charAt(i);

            if(token == '[' || token == '(' || token == '{' ) {     
                stackEval.push(token);
            } else if(token == ']') {
                if(stackEval.isEmpty() || stackEval.pop() != '[') {
                    return false;
                }
            } else if(token == ')') {
                if(stackEval.isEmpty() || stackEval.pop() != '(') {
                    return false;
                }           
            } else if(token == '}') {
                if(stackEval.isEmpty() || stackEval.pop() != '{') {
                    return false;
                }
            }
        }
        return stackEval.isEmpty();
       }



    //problem 2 algo to evaluate a post-fixed expression
    static int evaluatePostfix(String exp) throws EmptyStackException
    { 
        Stack<Integer> stackEval2 = new Stack<>(); 

        for(int i = 0; i < exp.length(); i++) 
        { 
            char c = exp.charAt(i); 

            if(c == ' ') 
            continue; 

            else if(Character.isDigit(c)) { 
                int n = 0; 

                while(Character.isDigit(c)) { 
                   n = n*10 + (int)(c-'0'); 
                    i++; 
                    c = exp.charAt(i); 
                } 
                i--; 

                stackEval2.push(n); 
            } 

            else { 

                try {
                //if operand pops two values to do the calculation through the switch statement
                int val1 = stackEval2.pop(); 

                int val2 = stackEval2.pop(); 
                //operands in a switch to test and do the operator's function each value grabbed and tested
                switch(c) { 
                    case '+': 
                    stackEval2.push(val2 + val1); 
                    break; 

                    case '-': 
                    stackEval2.push(val2 - val1); 
                    break; 

                    case '/': 
                    stackEval2.push(val2 / val1); 
                    break; 

                    case '*': 
                    stackEval2.push(val2 * val1); 
                    break; 
                } 
                } catch (EmptyStackException e) {
                    System.out.println("Ill-formatted");
                }
            } 
        } 
        return stackEval2.pop();  
    } 
}

1 个答案:

答案 0 :(得分:0)

一种简单设置输出格式的方法是将try-catch块放在调用evaluatePostfix()方法的位置(确保删除{{1} } try-catch方法内的代码段):

evaluatePostfix()

这样,当System.out.println("\n"); try (BufferedReader filereader2 = new BufferedReader(new FileReader("Problem2.txt"))) { while (true) { String line = filereader2.readLine(); if (line == null) { break; } try { System.out.println(evaluatePostfix(line)); } catch (EmptyStackException e) { System.out.println("Ill-formatted"); } } } 方法内部发生异常时,该方法将引发该异常,并且该异常将在循环之外进行处理,从而避免了重复的错误消息和其他不良影响。