2012-09-04 3 views
-1

방정식 해석 도구의 섹션에 문제가 있습니다. postfix 방정식을 유지하는 Object 배열이 있으며이 메서드는 각 값을 계산합니다.Java의 수식 해석기 - 스택에 푸시되지 않은 값

제가하는 데 문제는이 목록이 비어 있음을 말해 충돌하는 것입니다 (이 시점에서 : 더블 NUM1이 = (() operandStack.pop는()) 더블)

누군가가 나에게 무엇을 말할 수 내가 여기서 잘못 했니?

DSAQueue<Object> postfixQueue = new DSAQueue<Object>(); 
. 
. 
. 
. 


private double evaluatePostfix (Queue<Object> postfixQueue) 
{ 

DSAStack<Double> operandStack = new Stack<Double>(); 
while (postfixQueue.isEmpty() == false) 
    { 
    if (postfixQueue.peek() instanceof Double) 
     { 
     operandStack.push((Double)(postfixQueue.dequeue())); 
     } 
    else 
     { 
     double num1 = ((double)operandStack.pop()); 
     double num2 = ((double)operandStack.pop()); 
     char operator = ((char)postfixQueue.dequeue()); 
     double result = executeOperation (operator, num1, num2); 
     operandStack.push(result); 
     } 
    } 
double solution = operandStack.top(); 
return solution; 
} 
+1

당신은 어떤 방법으로 그 방법을 테스트 해 보았습니까? –

+2

내 생각 엔이 스택을 호출 할 때 스택이 비어 있다고 생각합니다. 디버거에서 코드를 단계별로 실행 해 보았습니까? –

+1

디버깅을 시도 했습니까? (첫 번째 반복에서 postfixQueue의 내용을 확인하십시오. 문제는 Double의 인스턴스가 아닌 첫 번째 요소 유형에 속한 것입니다. 그리고 빈 operandStack을 사용하여 else 케이스로 들어갑니다) – aviad

답변

2

아래 코드의 주석을 참조하십시오. 이 문제의 근본 원인이되는 경우 (자신의 의견에 피터에 의해 제안) 디버거를 통해 단계 경우

DSAQueue<Object> postfixQueue = new DSAQueue<Object>(); 

private double evaluatePostfix (Queue<Object> postfixQueue) 
{ 

    // Here you define an empty list 
    DSAStack<Double> operandStack = new Stack<Double>(); 

    while (postfixQueue.isEmpty() == false) 
    { 
    if (postfixQueue.peek() instanceof Double) 
    { 
     operandStack.push((Double)(postfixQueue.dequeue())); 
    } 
    else 
    { 
     // If the first item in postfixQueue was not a Double, you're now 
     // pop-ing from an empty stack 
     double num1 = ((double)operandStack.pop()); 
     double num2 = ((double)operandStack.pop()); 
     char operator = ((char)postfixQueue.dequeue()); 
     double result = executeOperation (operator, num1, num2); 
     operandStack.push(result); 
    } 
    } 
    double solution = operandStack.top(); 
    return solution; 
} 

, 당신이 식별 할 수 있습니다 오류가 발생 사소한 코드 경로가있는 것 같습니다 .

+0

고마워. 이론적으로 postfixQueue의 첫 번째 항목은 두 배가 될 것이므로 postfixQueue를 넣을 때 오류가 발생했다고 생각합니다. – Dawson

+0

DSAQueue 클래스가 반짝이는'toString' 메소드를 제공하지 않는다면, 가장 쉬운 방법은 큐를 반복하고 각 객체에 대해'toString'을 출력하는 것입니다. 내 대답이 원래의 문제를 해결했다면, [받아 들일 수있는 것으로 표시해야합니다] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)하고 게시하십시오. 별도의 질문으로 추가 문제 (철저한 연구 후, 물론). –

관련 문제