返回postfix无效表达式

时间:2017-04-22 17:40:29

标签: java stack postfix

所以我想解决一些问题。我必须返回后缀表达式的结果,但还必须检测无效的后缀表达式。我的问题是,每当我检测到无效的后缀表达式时,程序仍会返回表达式的值。我只想返回一条消息,指出表达式无效。

代码:

public class Evaluator {

    private static final String add = "+"; 
    private static final String sub = "-";
    private static final String mul = "*";
    private static final String div = "/";

    public static void main (String [] args) throws FileNotFoundException{
        Scanner scan = new Scanner(System.in);

        System.out.print("Input filename:"); // read file -------
        String filename = scan.nextLine();
        File file = new File(filename);
        Scanner reader = new Scanner(file);// --------------------------


        while (reader.hasNextLine()){
        String  line = reader.nextLine();
        System.out.println(line + " = " + start(line));
        }

    }

    public static int start (String line ) {
        GenericStack<Integer> stack = new GenericStack<>();

         String[] inputs = line.split(" ");
        return postfix(stack, inputs);

    }
    public static int postfix(GenericStack<Integer> stack, String[] temp) {
        int num1, num2;

        for(int i = 0; i < temp.length; i++) {
            if( temp[i].equals(add) || temp[i].equals(sub) || temp[i].equals(mul) || temp[i].equals(div) ) {
                num2 = stack.pop();
                num1 = stack.pop();
                switch(temp[i]) {
                case add: {
                    int operation = num1 + num2;
                    stack.push(operation);
                    break;
                }

                case sub: {
                    int operation = num1 - num2;
                    stack.push(operation);
                    break;
                }

                case mul: {
                    int operation = num1 * num2;
                    stack.push(operation);
                    break;
                }

                case div: {
                    int operation = num1 / num2;
                    stack.push(operation);
                    break;
                }
                }
            } else {            
                stack.push(Integer.parseInt(temp[i]));
            }

        }
        if (stack.isEmpty()) {
            System.out.print ("No value to return on the following postfix expression: ");  
        }
         if (stack.size() > 1) {
             System.out.print ("Too many operands on the following postfix expression: ");   
        }

     return stack.pop();

    }
}

示例输出:

6 5 2 3 + 8 * + 3 + * = 288
Too many operands on the following postfix expression: 6 5 2 3 + 8 * + 3 + = 48

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是抛出异常

更改postfix方法在Invalid表达式上抛出Exception并在方法签名上添加throws Exception如下所示:

<?php
    //get values from index.php

    $lecturerid = $_POST['studentid'];
    $password = $_POST['Pass'];

   // Create connection
   $conn = mysqli_connect("localhost", "root", "", "coursework");

   // Check connection
   if (!$conn) {
          die("Connection failed: " . mysqli_connect_error());
   }
   echo "Connected successfully";

   //Build query
   $sql = "INSERT INTO studentlogin (studentid, password) VALUES ('John', 'Doe')";

   //execute query
   mysqli_query($conn,$sql) or die(mysqli_error($conn));

?>

更改start方法add throws方法签名上的异常

public static int postfix(GenericStack<Integer> stack, String[] temp) throws Exception {
    ....
    if (stack.isEmpty()) {
        throw new Exception("No value to return on the following postfix expression: ");
    }
    if (stack.size() > 1) {
        throw new Exception("Too many operands on the following postfix expression: ");
    }
}

在main方法中,在调用方法start

上添加try catch块
public static int start(String line) throws Exception {
    ....
}