-2

When i run the code it gives an error

java.lang.ArrayIndexOutOfBoundsException: 0
    at SearchFile.main(SearchFile.java:28)

MyNote.txt is the text file saved in D directory of my computer. whereas "ad" is the word in that text file.

import java.io.*;

public class SearchFile {

public static void main(String args[]) {

args[0] = "ad";

if (args.length > 0) {
String searchword = args[0];

try {

int LineCount = 0;
String line = "";

BufferedReader bReader = new BufferedReader(new FileReader("D:/MyNote.txt"));

while ((line = bReader.readLine()) != null) {
LineCount++;

int posFound = line.indexOf(searchword);
if (posFound > - 1) {
System.out.println("Search word found at position " + posFound + " on line " + LineCount);
}
}
bReader.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
}
else {
System.out.println("Please provide a word to search the file for.");
}
}
}

i dont know what the error is or what i have done wrong. i am new to this actually please help!! THANK YOU

newbieee
  • 1
  • 2
  • You are assigning a value to args[0] without checking to see if there is even such an index to set. In other words, if there are no arguments that have been given to the main method then args[0] will throws an `ArrayIndexOutOfBoundsException` as there is no such array index. – Rabbit Guy Apr 18 '16 at 15:18

2 Answers2

0

The problem is that your args[] is empty and has no size when your application starts. In this case there exists no index 0 and your line with args[0] = "ad"; fails.

Try to start your application with an argument instead of trying to set it manually in the code. If you do not see any other solution create an array yourself and set it as the variable filled with the information you want to use.

GHajba
  • 3,665
  • 5
  • 25
  • 35
0

Use the another variable instead than args[0]:

String str = "ad";
if (str.length() > 0) {
String searchword = str;

The variable args[0] is used as an input to the class through the main method. Moreover it's empty in your case because no arguments were given.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183