1

我是学习java的新手,请帮助我解决问题。我的代码有什么问题???请在我运行此代码时帮助我,然后我发现错误 ArrayIndexOutOfBoundException

public class SearchForFile {

static File file;
String[] args = null;
        public static void main(String args[]) {

            try {
                // Open the file c:\test.txt as a buffered reader

                BufferedReader bf = new BufferedReader(new FileReader("D:\\test.txt"));



                // Start a line count and declare a string to hold our current line.

                int linecount = 0;

                    String line;



                // Let the user know what we are searching for

                System.out.println("Searching for " + args[0] + " in file...");



                // Loop through each line, stashing the line into our line variable.

                while (( line = bf.readLine()) != null)

                {

                        // Increment the count and find the index of the word

                        linecount++;

                        int indexfound = line.indexOf(args[0]);



                        // If greater than -1, means we found the word

                        if (indexfound > -1) {

                             System.out.println("Word was found at position " + indexfound + " on line " + linecount);

                        }

                }



                // Close the file after done searching

                bf.close();

            }      

            catch (IOException e) {

                System.out.println("IO Error Occurred: " + e.toString());

            }

            }} 

在这段代码中,我发现这个错误 kindle 帮助我解决了这个问题

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ForFile.main(ForFile.java:39)
4

2 回答 2

3

始终保持防御,你应该设计你的代码,使它不应该失败,如果它确实存在,或者优雅地失败。

有两种方法可以解决上述问题。

第一:arg在访问之前检查它的大小

if (arg.length == 1) //Do Stuff with arg[0]

您可以更改上面的 if 语句以您喜欢的方式解决它,所以假设您要求用户输入三个参数,如果没有三个参数,您的程序将无法继续。尝试:

if (arg.length != 3) //Stop the loop and tell the users that they need 3 args

第二:封装arg[0]在一个try一个catch中,所以在你的while循环里面

try
{
    int indexfound = line.indexOf(args[0]);
    linecount++;
    if (indexfound > -1)
        System.out.println("Word was found at position " + indexfound + " on line " + linecount);

}
catch (ArrayIndexOutOfBoundsException e)
{
    System.out.println("arg[0] index is not initialized");
}

希望这可以帮助。

于 2013-06-23T10:22:05.900 回答
1

好吧,我们不知道它到底是哪一行,但我猜它发生在这一行:

System.out.println("Searching for " + args[0] + " in file...");

发生这种情况是因为您在启动应用程序时没有将任何程序参数传递给应用程序。尝试:

java SearchForFile word
于 2013-06-23T10:13:17.387 回答