2011-10-09 2 views
0

infix 표현식을 접미사로 변환 한 후 초안을 평가하는 초보자 용 Java 응용 프로그램에서 작업하고 있습니다. 다음과 같은 오류 메시지를 수정하는 데 많은 시간을 보냈습니다.인터페이스 클래스 호출에서보고되지 않은 예외

Interface.java:21: error: unreported exception SyntaxErrorException; must be caught or declared to be thrown 

String conversion = infix.convert(str); 
                   ^
Interface.java:22: error: unreported exception SyntaxErrorException; must be caught or declared to be thrown 

System.out.println(postfix.eval(conversion)); 
                  ^
2 errors 

이 오류로 도움을받을 수 있습니까? 나는 try/catch 구문을 사용하고 SyntaxErrorException 클래스를 움직이는 것을 망설였다. 그러나 나는 아직 행운을 얻지 못했다.

Interface.java 유용한 힌트이나 솔루션에 미리

import java.util.*; 

/** 
* Interface: 
*/ 
class Interface { 
    /** 
    * 
    */ 
    public static void main(String [ ] args) 
    { 
     String str = ""; 
     Scanner keyboard = new Scanner (System.in);   
     InfixToPostfix infix = new InfixToPostfix(); 
     PostfixEvaluator postfix = new PostfixEvaluator(); 

     System.out.println("Enter expressions, one per line:"); 
      while((str = keyboard.next()) != null) 
      { 
       System.out.println("Read: " + str); 
       String conversion = infix.convert(str); 
       System.out.println(postfix.eval(conversion)); 
       System.out.println("Enter next expression:"); 
      } 
    } 
} 

InfixToPostfix.java

import java.util.*; 

/** 
* Translates an infix expression to a postfix expression. 
*/ 

public class InfixToPostfix { 

    // Nested Class 
    /** Class to report a syntax error. */ 
    public static class SyntaxErrorException 
     extends Exception { 
    /** Construct a SyntaxErrorException with the specified 
     message. 
     @param message The message 
    */ 
    SyntaxErrorException(String message) { 
     super(message); 
    } 
    } 

    // Data Fields 
    /** The operator stack */ 
    private Stack <Character> operatorStack; 

    /** The operators */ 
    private static final String OPERATORS = "+-*/"; 

    /** The precedence of the operators, matches order in OPERATORS. */ 
    private static final int[] PRECEDENCE = { 
     1, 1, 2, 2}; 

    /** The postfix string */ 
    private StringBuilder postfix; 

    /** Convert a string from infix to postfix. 
     @param infix The infix expression 
     @throws SyntaxErrorException 
    */ 
    public String convert(String infix) throws SyntaxErrorException { 
    operatorStack = new Stack <Character>(); 
    postfix = new StringBuilder(); 
    StringTokenizer infixTokens = new StringTokenizer(infix); 
    try { 
     // Process each token in the infix string. 
     while (infixTokens.hasMoreTokens()) { 
     String nextToken = infixTokens.nextToken(); 
     char firstChar = nextToken.charAt(0); 
     // Is it an operand? 
     if (Character.isJavaIdentifierStart(firstChar) 
      || Character.isDigit(firstChar)) { 
      postfix.append(nextToken); 
      postfix.append(' '); 
     } // Is it an operator? 
     else if (isOperator(firstChar)) { 
      processOperator(firstChar); 
     } 
     else { 
      throw new SyntaxErrorException 
       ("Unexpected Character Encountered: " 
       + firstChar); 
     } 
     } // End while. 

     // Pop any remaining operators and 
     // append them to postfix. 
     while (!operatorStack.empty()) { 
     char op = operatorStack.pop(); 
     postfix.append(op); 
     postfix.append(' '); 
     } 
     // assert: Stack is empty, return result. 
     return postfix.toString(); 
    } 
    catch (EmptyStackException ex) { 
     throw new SyntaxErrorException 
      ("Syntax Error: The stack is empty"); 
    } 
    } 

    /** Method to process operators. 
     @param op The operator 
     @throws EmptyStackException 
    */ 
    private void processOperator(char op) { 
    if (operatorStack.empty()) { 
     operatorStack.push(op); 
    } 
    else { 
     // Peek the operator stack and 
     // let topOp be top operator. 
     char topOp = operatorStack.peek(); 
     if (precedence(op) > precedence(topOp)) { 
     operatorStack.push(op); 
     } 
     else { 
     // Pop all stacked operators with equal 
     // or higher precedence than op. 
     while (!operatorStack.empty() 
       && precedence(op) <= precedence(topOp)) { 
      operatorStack.pop(); 
      postfix.append(topOp); 
      postfix.append(' '); 
      if (!operatorStack.empty()) { 
      // Reset topOp. 
      topOp = operatorStack.peek(); 
      } 
     } 
     // assert: Operator stack is empty or 
     //   current operator precedence > 
     //   top of stack operator precedence. 
     operatorStack.push(op); 
     } 
    } 
    } 

    /** Determine whether a character is an operator. 
     @param ch The character to be tested 
     @return true if ch is an operator 
    */ 
    private boolean isOperator(char ch) { 
    return OPERATORS.indexOf(ch) != -1; 
    } 

    /** Determine the precedence of an operator. 
     @param op The operator 
     @return the precedence 
    */ 
    private int precedence(char op) { 
    return PRECEDENCE[OPERATORS.indexOf(op)]; 
    } 
} 

PostfixEvaluator.java

import java.util.*; 

/** 
* Class that can evaluate a postfix expression. 
* */ 

public class PostfixEvaluator { 

    // Nested Class 
    /** Class to report a syntax error. */ 
    public static class SyntaxErrorException 
     extends Exception { 
    /** Construct a SyntaxErrorException with the specified 
     message. 
     @param message The message 
    */ 
    SyntaxErrorException(String message) { 
     super(message); 
    } 
    } 

    // Constant 
    /** A list of operators. */ 
    private static final String OPERATORS = "+-*/"; 

    // Data Field 
    /** The operand stack. */ 
    private Stack <Integer> operandStack; 

    // Methods 
    /** Evaluates the current operation. 
     This function pops the two operands off the operand 
     stack and applies the operator. 
     @param op A character representing the operator 
     @return The result of applying the operator 
     @throws EmptyStackException if pop is attempted on 
       an empty stack 
    */ 
    private int evalOp(char op) { 
    // Pop the two operands off the stack. 
    int rhs = operandStack.pop(); 
    int lhs = operandStack.pop(); 
    int result = 0; 
    // Evaluate the operator. 
    switch (op) { 
     case '+': 
     result = lhs + rhs; 
     break; 
     case '-': 
     result = lhs - rhs; 
     break; 
     case '/': 
     result = lhs/rhs; 
     break; 
     case '*': 
     result = lhs * rhs; 
     break; 

    } 
    return result; 
    } 

    /** Determines whether a character is an operator. 
     @param op The character to be tested 
     @return true if the character is an operator 
    */ 
    private boolean isOperator(char ch) { 
    return OPERATORS.indexOf(ch) != -1; 
    } 

    /** Evaluates a postfix expression. 
     @param expression The expression to be evaluated 
     @return The value of the expression 
     @throws SyntaxErrorException if a syntax error is detected 
    */ 
    public int eval(String expression) throws SyntaxErrorException { 
    // Create an empty stack. 
    operandStack = new Stack <Integer>(); 

    // Process each token. 
    StringTokenizer tokens = new StringTokenizer(expression); 
    try { 
     while (tokens.hasMoreTokens()) { 
     String nextToken = tokens.nextToken(); 
     // Does it start with a digit? 
     if (Character.isDigit(nextToken.charAt(0))) { 
      // Get the integer value. 
      int value = Integer.parseInt(nextToken); 
      // Push value onto operand stack. 
      operandStack.push(value); 
     } // Is it an operator? 
     else if (isOperator(nextToken.charAt(0))) { 
      // Evaluate the operator. 
      int result = evalOp(nextToken.charAt(0)); 
      // Push result onto the operand stack. 
      operandStack.push(result); 
     } 
     else { 
      // Invalid character. 
      throw new SyntaxErrorException(
       "Invalid character encountered"); 
     } 
     } // End while. 

     // No more tokens - pop result from operand stack. 
     int answer = operandStack.pop(); 
     // Operand stack should be empty. 
     if (operandStack.empty()) { 
     return answer; 
     } 
     else { 
     // Indicate syntax error. 
     throw new SyntaxErrorException(
      "Syntax Error: Stack should be empty"); 
     } 
    } 
    catch (EmptyStackException ex) { 
     // Pop was attempted on an empty stack. 
     throw new SyntaxErrorException(
      "Syntax Error: The stack is empty"); 
    } 
    } 
} 

감사 : 여기에 지금까지 내 프로그램입니다.

+0

문제는 예외가 내부 클래스로 선언하는 것입니다, 당신은 중복 된 이름이 있습니다. 그러지 마. –

답변

1

오류는 checked exception that you haven't handled이 있음을 알려줍니다. "Checked"는 컴파일러가 강제로 무언가를하도록 강요하며 무시할 수 없다는 것을 의미합니다. try/catch 블록을 사용하여 catch하거나 문제가 발생한 메서드가이 예외를 throw하는지 선언해야합니다. 이 경우, 주된 메소드는 convert()와 eval()을 호출하는 것이며, 둘 다 SyntaxErrorException을 발생시킵니다. 즉, convert() 및 eval()을 중심으로 try/catch가 필요하다면 main은 throws SyntaxErrorException을 선언해야합니다.

편집 : 아, 충분히 자세히 보지 않았습니다. 문제는 두 가지 다른 SyntaxErrorExceptions가 있다는 것입니다. 단 오류 메시지가 간단한 클래스 이름 만 제공하기 때문에 구별하기가 어렵습니다. 정말로 두 가지 예외가 필요합니까? 그들이 동일한 이름을 가지고 있다는 사실은 그렇지 않다는 것을 의미합니다. 어쨌든 현재 상황에서는 예외를 처리해야합니다. 어느

public static void main(String[] args) throws InfixToPostfix.SyntaxErrorException, PostfixEvaluator.SyntaxErrorException { 

또는

try { 
    String conversion = infix.convert(str); 
    System.out.println(postfix.eval(conversion)); 
} catch (InfixToPostfix.SyntaxErrorException e) { 
    ... 
} catch (PostfixEvaluator.SyntaxErrorException e) { 
    ... 
} 
+0

이전에 try/catch 문을 호출하기 전에 시도했습니다. 결과는 동일한 오류 및 다음과 같은 새로운 오류가 발생합니다. SyntaxErrorException 해당 try 문의 본문에서 절대로 throw되지 않습니다. – me0w0r

+0

나는 또한 "main throws SyntaxErrorException"으로 메인을 변경하려고 시도했다. 그러나 이것은 에러를 제거하지는 못할 것이다. SyntaxErrorException 클래스에 대한 코드를 다시 작성하여 차이가 있는지 확인해 보겠습니다. – me0w0r

+0

문제가 있습니다. 내 대답이 업데이트되었습니다. –