V
V
v_vladik2022-01-16 13:52:11
Java
v_vladik, 2022-01-16 13:52:11

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

1 answer(s)
A
Alexey Ukolov, 2022-01-16
@v_vladik

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 question

Ask a Question

731 491 924 answers to any question