Click here to Skip to main content
15,671,149 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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<string> words = new ArrayList<string>();
ArrayList<string> hints = new ArrayList<string>();
while (fSc.hasNext())
{
String[] w = fSc.nextLine().split("."); // Split secret words from hints
words.add(w[0]);
hints.add(w[1]);
}
Posted

1 solution

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
 
Share this answer
 
Comments
ZurdoDev 3-Dec-15 15:07pm    
+5
Sergey Alexandrovich Kryukov 3-Dec-15 15:34pm    
Thank you, Ryan.
—SA
Member 12184414 3-Dec-15 16:14pm    
Thank you, Sergey!
Sergey Alexandrovich Kryukov 3-Dec-15 16:30pm    
You are very welcome.
Good luck, call again.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900