Hello,
Could you please clarify why my code (part of it provided below) throws the following exception when I am trying to split my words from hints separated by a period in my text file:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at name.main(name.java:92) "92" corresponds to words.add(w[0]); in the code below:
File f = new File("name.txt");
Scanner fSc = new Scanner(f);
ArrayList words = new ArrayList();
ArrayList hints = new ArrayList();
while (fSc.hasNext())
{
String[] w = fSc.nextLine().split("."); // Split secret words from hints
words.add(w[0]);
hints.add(w[1]);
}
解决方案
This is because the array contains less elements than you assume. This exception on w[0] means that the string array is empty. If it was on w[1], it would mean that the array has less than 2 elements. If the array was null, exception would be different, null reference exception. Why it happened in your case? Use the debugger. In all cases, you cannot not assume certain array length, need to check it up before addressing by index.
—SA