Reputation: 69
I am new in to learn java please help me to resolve the issue. whats wrong with my code??? please help me when i run this code then i find the error 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());
}
}}
In this code I find this error kindle help me to resolve the issue
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ForFile.main(ForFile.java:39)
Upvotes: 1
Views: 196
Reputation: 7994
Always be defensive, you should design your code so it shouldn't fail, and if it does it exists gracefully, or fails gracefully.
There are two ways you can solve the above problem.
First: Check the size of the arg
before accessing it
if (arg.length == 1) //Do Stuff with arg[0]
You can change the above if statment to solve it the way you like, so say you require the user to input to enter three arguments and without three arguments your program can not continue. try:
if (arg.length != 3) //Stop the loop and tell the users that they need 3 args
Second: Encapsulate the arg[0]
in a try an catch, so Inside your while
loop
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");
}
Hope this helps.
Upvotes: 3
Reputation: 9775
Well, we don't know what line is it exactly, but I guess it's happening in this line:
System.out.println("Searching for " + args[0] + " in file...");
It happens because you don't pass any program arguments to the application when you start it. Try:
java SearchForFile word
Upvotes: 1