繁体   English   中英

TXT文件中的Java堆栈评估

[英]Java Stack Evaluation from TXT file

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

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

Problem2.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();  
    } 
}

一种将输出格式化为所需格式的简单方法是,将try-catch块放在您调用evaluatePostfix()方法的位置(请确保删除位于evaluatePostfix()方法内部的try-catch ):

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");
        }
    }
}

这样,当在evaluatePostfix()方法内部发生异常时,该方法将引发该异常,并且该异常将在循环之外进行处理,从而避免了重复的错误消息和其他不良影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM