这段代码有什么问题?

时间:2013-06-23 10:10:57

标签: java

我是新手学习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());

            }

            }} 

在此代码中,我发现此错误有助于我解决问题

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

2 个答案:

答案 0 :(得分:3)

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

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

首先:在访问之前检查arg的大小

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

你可以改变上面的if if statment以你喜欢的方式解决它,所以说你要求用户输入以输入三个参数而没有三个参数你的程序无法继续。尝试:

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

第二个:arg[0]封装在一个试用版中,因此在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");
}

希望这有帮助。

答案 1 :(得分:1)

好吧,我们不知道究竟是哪一行,但我想这是在这一行:

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

这是因为启动时不会将任何程序参数传递给应用程序。尝试:

java SearchForFile word