2017-04-22 78 views
0

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

代码:

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 

回答

0

做,这是抛出异常

变化无效表达后缀方法抛出异常,并添加最佳方式抛出异常方法签名如下:

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

更改启动方式添加抛出的方法签名

public static int start(String line) throws Exception { 
    .... 
} 

异常,并在主要方法上调用方法添加try catch块开始

try { 
    System.out.println(line + " = " + start(line)); 
} catch (Exception e) { 
    System.out.println(e.getMessage()); 
}