为什么我得到一个String out of bounds异常

时间:2011-09-13 17:48:49

标签: java

我有以下代码从文件中读取数据并将其存储在String变量中,现在当我运行它时,它给了我一个字符串超出范围的异常。我该如何解决这个错误?

运行命令和错误:

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");

    }
}

3 个答案:

答案 0 :(得分: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') 

以上代码是您的问题。请注意, i 0 - (length - 1),这意味着 charAt(i)即可。但是,您执行 i ++ 并执行另一个 charAt(i)。因此,当 i == length -1 时, i + 之后的 charAt 会导致异常。

答案 1 :(得分:1)

默认情况下,您的for循环失败。如果你达到';'在该行的末尾,例如:'if(true);'然后你增加i并测试下一个char是不是'i'..这显然会引发OoB异常,因为你要求索引大于string.length - 1;

答案 2 :(得分:0)

您的代码中存在许多问题。例如。当你做这样的事情时:

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

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

你在脚下射击自己。当我指向这里的最后一个字符时,你会在第二个字符中得到错误。我强烈反对这种嵌套的“if”检查你正在尝试做什么。它可能是代码中无限的错误源。看看“开关”声明:

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