2013-10-26 83 views
-2
 if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var")) 
     { 
      int value = 0; 
      for(int i=0; i<tokens.length; i++) 
      { 
       if(tokens[i].charAt(0) == '+'); 
       { 
        if(Character.isDigit(tokens[i].charAt(0))) 
        { 
         int add = Integer.parseInt(tokens[i]); 
         value = value + add; 
        } 
       } 
       else 
       { 
        System.out.println("No symbol"); 
        break; 
       } 
      } 
      map.put(tokens[0], value); 
      System.out.println(map); 
     } 

「無符號」的else語句返回一個沒有if語句的錯誤。爲什麼我的代碼表示else語句沒有if語句?

回答

5

您有多餘的分號您if

if(tokens[i].charAt(0) == '+'); 

這分號之後將有效地如果if條件爲真時執行該塊。那麼下面的塊將被無條件執行,因此else與之前的if無關。

只要刪除該分號,它會解決您的問題。

2

見分號if語句

if(tokens[i].charAt(0) == '+'); 

應該

if(tokens[i].charAt(0) == '+') 
2

結束時,您的if語句錯誤地關閉。

  if(tokens[i].charAt(0) == '+') // notice the missing ";" 
      { 

您的代碼

  if(tokens[i].charAt(0) == '+'); // if statement ends 
      {             // code block 
       if(Character.isDigit(tokens[i].charAt(0))) 
       { 
        int add = Integer.parseInt(tokens[i]); 
        value = value + add; 
       } 
      } 
      else   // ERROR because the compiler finds an else block but no preceding if block 
      { 
       System.out.println("No symbol"); 
       break; 
      }