Answer the question
In order to leave comments, you need to log in
Why am I getting an ArrayIndexOutOfBoundsException exception?
I have this sample code. My plans are to read a row from a file that stores words and their translations. English words are stored in the "words" sheet, and their translations are stored in "translation". I have implemented two getters, but the problem with the second one is ArrayIndexOutOfBoundsException. What is the problem?
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("english.txt");
Scanner sc = new Scanner(file);
int size = 0;
List<String> list = new ArrayList<>();
List<String> words = new ArrayList<>();
List<String> translation = new ArrayList<>();
while (sc.hasNextLine()) {
list.add(sc.nextLine());
size++;
}
for (int i = 0; i < size; i++) {
words.add(getFirstLine(list.get(i)));
translation.add(getSecondLine(list.get(i)));
}
}
public static String getFirstLine(String line) {
String[] lines = line.split("-");
return lines[0];
}
public static String getSecondLine(String line) {
String[] lines = line.split("-");
return lines[1];
}
}
Answer the question
In order to leave comments, you need to log in
Obviously, you have lines in the file that don't have "-"
, and therefore there is no second element in the array after split.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question