2011-09-13 80 views
0

我有下面的代碼從文件讀取數據並將其存儲在一個字符串變量,現在當我運行它,它給了我一個字符串越界異常。我該如何解決這個錯誤?爲什麼我得到一個字符串越界異常

運行命令和錯誤:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1882 
    at java.lang.String.charAt(String.java:694) 
    at IfCounter2.main(IfCounter2.java:92) 

代碼:

import java.io.*; 

public class IfCounter2 
{ 
    // method to check if there is a single-line comment 
    public static boolean lineAComment(String line) 
    { 
     if (line.contains("//")) 
      return true; 

     return false; 
    } 

    // method to check if there is a multi-line comment start 
    public static boolean multiLineCommentStart(String line) 
    { 
     if (line.contains("/*")) 
      return true; 

     return false; 
    } 

    // method to check if there is a multi-line comment end 
    public static boolean multiLineCommentEnd(String line) 
    { 
     if (line.contains("*/")) 
      return true; 

     return false; 
    } 

    public static void main(String[] args) throws IOException 
    { 
     // variable to keep track of ifs 
     int ifCount = 0; 
     // check how many arguments are passed 
     int numArgs = args.length; 

     // look at all the arguments 

     // they don't want to count ifs in comments ************************************ --nocomment was entered 
     if (args[0].equals("--nocomments")) 
     { 
      // create a new BufferReader for the file that will be at args 1 
      BufferedReader reader = new BufferedReader(new FileReader (args[1])); 
      String line = null; 
      StringBuilder stringBuilder = new StringBuilder(); 
      String ls = System.getProperty("line.separator"); 

      // read from the text file 
      boolean multiLineComment = true; 

      // ignore comments as we store data in a String variable 
      while ((line = reader.readLine()) != null) 
      { 
       if (!multiLineCommentStart(line)) 
       { 
        multiLineComment = true; 
       } // end if 

       if (multiLineComment) 
       { 
        if (!multiLineCommentEnd(line)) 
        { 
         multiLineComment = false; 
        } // end if 
       } // end if 

       if (!lineAComment(line) && !multiLineComment) 
       { 
        stringBuilder.append(line); 
        stringBuilder.append(ls); 
       } // end if 
      } // end while 

      // create a new string with stringBuilder data 
      String tempString = stringBuilder.toString(); 
      System.out.println(tempString); 

      // create one last string to look for our valid if(s) in, 
      // with ALL whitespace removed 
      String compareString = tempString.replaceAll("\\s",""); 
      //System.out.println(compareString); 

      for (int i = 0; i < compareString.length(); i++) 
      { 

       if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{' || compareString.charAt(i) == '\n') 
       { 
        i++; 

        if (compareString.charAt(i) == 'i') 
        { 
         i++; 

         if (compareString.charAt(i) == 'f') 
         { 
          i++; 

          if (compareString.charAt(i) == '(') 
           ifCount++; 
         } // end if 
        } // end if 
       } // end if 

      } // end for 

     } // end if (comments option) 

     // else ******************************************************** count ifs as usual 
     /*else 
     { 
      for (int c = 0; c <= numArgs; c++) 
      { 
       // create a new BufferReader 
       BufferedReader reader2 = new BufferedReader(new FileReader (args[c])); 
       String line2 = null; 
       StringBuilder stringBuilder2 = new StringBuilder(); 
       String ls2 = System.getProperty("line.separator"); 

       // read from the text file 
       while ((line2 = reader2.readLine()) != null) 
       { 
        stringBuilder2.append(line2); 
        stringBuilder2.append(ls2); 
       } 

       // create a new string with stringBuilder data 
       String tempString2 = stringBuilder2.toString(); 

       // create one last string to look for our valid if(s) in 
       // with ALL whitespace removed 
       String compareString2 = tempString2.replaceAll("\\s",""); 

       // check for valid if(s) 
       for (int i = 0; i < compareString2.length(); i++) 
       { 
        if (compareString2.charAt(i) == ';' || compareString2.charAt(i) == '}' || compareString2.charAt(i) == '{') // added opening "{" for nested ifs :) 
        { 
         i++; 

         if (compareString2.charAt(i) == 'i') 
         { 
          i++; 

          if (compareString2.charAt(i) == 'f') 
          { 
           i++; 

           if (compareString2.charAt(i) == '(') 
            ifCount++; 
          } // end if 
         } // end if 
        } // end if 

       } // end for 
      } // end if (else option) 
     } // end for 
*/  
     // print the number of valid "if(s) with a new line after" 
     System.out.println(ifCount + "\n"); 

    } 
} 
+1

您是否嘗試過使用調試器並在第92行設置斷點?從那裏,你可以檢查變量並精確確定爲什麼傳遞給'charAt'的索引是無效的。 –

+0

什麼行代碼在92行? –

+0

我不確定這段代碼的目的是什麼,但顯然是不正確的。如果它應該解析Java代碼..所以你不能識別是(true); (假);在一行中作爲兩個ifs;)你將只計算一個。 –

回答

5
for (int i = 0; i < compareString.length(); i++) 
     { 

      if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{' || compareString.charAt(i) == '\n') 
      { 
       i++; 

       if (compareString.charAt(i) == 'i') 

上面的代碼是你的問題。請注意,0 - (長度 - 1)這意味着charAt(i)是好的。然而,你做i ++並做另一個charAt(i)。所以當i ==長度-1,charAti ++會引起異常。

+0

我該如何解決這個問題呢?我需要查看字符串中的所有字符。 – josh

+0

你可以在** ** ++ **之後檢查** i

+1

將它與字符串的長度比較,然後將其加一。 (if(compareString.length()<= i)break;)更好的方法可能是讓主循環只返回compareString.length() - 3(因爲循環的內容在結尾附近不相關) 。 – Rontologist

0

您的代碼中存在一堆問題。例如。當你做這樣的事情:

if (compareString.charAt(i) == 'i') 
    { 
     i++; 

     if (compareString.charAt(i) == 'f') 
     { 

你正在拍攝自己的腳。當我指向這裏的最後一個字符時,你會在第二個if中得到一個錯誤。我強烈勸阻這種嵌套的「if」檢查你想要做什麼。它可能是代碼中無限的錯誤來源。看看「開關」聲明:

switch(compareString.charAt(i)) { 
    case 'i': 
     // do something 
     break; 
    case 'f': 
     // do something else 
     break; 
} 
1

您的for循環默認情況下失敗。如果你達到';'例如:'if(true);'你然後增加我並測試下一個字符是否不是'我'..這顯然拋出OoB異常,因爲你問的索引大於string.length - 1;