2017-11-18 12 views
0

shunting yard 알고리즘에 대한 메소드를 작성하기 전에 여기에서 메소드를 작성하여 후위 표현식을 평가할 수 있습니다. postfix 대기열에서 수행 할 수 있도록이 calculate 메서드를 호출합니다. 내가 "변환"변환 할 때 double을 String으로 변환하려고 할 때 해석 할 수없는 변수

while(!(token==null)) { 
     if(isOperator(token)) { 
      double operand_2 = Double.parseDouble(polish.pop()); 
      double operand_1 = Double.parseDouble(polish.pop()); 
      if(token.contains("+")) { 
       double result = operand_2 + operand_1; 
      } 
      else if(token.contains("-")) { 
       double convert = operand_2 - operand_1; 
      } 
      else if(token.contains("/")) { 
       double convert = operand_2/operand_1; 
      } 
      else if(token.contains("*")) { 
       double convert = operand_2/operand_1; 
      } 

을 읽을 수있는 토큰이있는 동안

public String calculate(Queue post, Stack polish) { 

난 내 큐 큐에서 개별 토큰으로 분리해서 것은

String token = post.Dequeue(); 

읽을 수 String으로 전환하면 convert가 변수로 변환 될 수 없음을 알립니다.

  String result = Double.toString(convert); 
      polish.push(result); 
     } 
     else if(isNumeric(token)){ 
      polish.push(token); 
     } 
     String finalVal = polish.pop(); 
     return finalVal; 
    } 
} 
+0

Plz은 투표 및 동의하는 것을 잊지 마세요 –

답변

1

이것은 범위 문제입니다. 변수를 선언하면 선언은 { 문자가 이미 통과 한 문자 중 다음 문자 인 } 문자까지 지속됩니다. 각 if 또는 else if 블록 안에 convert을 선언 했으므로 선언은 해당 블록의 끝까지 지속됩니다.

는 당신이 필요가있는 무엇을 선언하면 convert를 사용하는 데 필요한 포인트까지 지속되도록 모든 ifelse 문 앞에 double convert;을 선언하는 것입니다.

연산자가 ifelse if 문과 일치하지 않는 경우를 처리하기 위해 double convert = 0;과 같은 초기 값을 지정할 수도 있습니다. 그렇지 않으면 다른 컴파일 오류로 종료 될 수 있습니다.

1

해당 범위 내에 convert을 정의하지 않았습니다. 변수로 선언되지 않으므로 오류가 발생합니다.

변경하려면 :

double convert; 
    while(!(token==null)) { 
      if(isOperator(token)) { 
       double operand_2 = Double.parseDouble(polish.pop()); 
       double operand_1 = Double.parseDouble(polish.pop()); 
       if(token.contains("+")) { 
        double result = operand_2 + operand_1; 
       } 
       else if(token.contains("-")) { 
        convert = operand_2 - operand_1; 
       } 
       else if(token.contains("/")) { 
        convert = operand_2/operand_1; 
       } 
       else if(token.contains("*")) { 
        convert = operand_2/operand_1; 
       }