1

Unsure if the spacing in the text file is causing the error or something else I didn't see. Just like the title says, I keep getting the array index out of bounds exception. I have no idea why, any help is appreciated.

For better reference (I copy and paste the text file into a Pastebin): https://pastebin.com/reYraNpY

public static void main(String[] args) throws FileNotFoundException
 {
   Map<String, Integer> sort = storeText();
   System.out.println("State: \t\t  Population:");
   for (Map.Entry<String, Integer> key : sort.entrySet())
   {
    System.out.printf("%-20s %d%n", key.getKey(), key.getValue());     
   }   
 }

public static Map<String, Integer> storeText() throws FileNotFoundException
{
   Map<String, Integer> map = new HashMap<String, Integer>();
   
   FileInputStream file = new FileInputStream("Assignment1CData.txt");
   Scanner input = new Scanner(file);
   while (input.hasNextLine())
    {
       String[] trim = input.nextLine().split(",");
       String[] trim2 = trim[1].split("   ");
       String state = trim2[0].replace(" ", ""); 
       Integer totalPopulation = Integer.parseInt(trim2[1]);

       map.put(state, map.getOrDefault(state, map.getOrDefault(state, 0) + totalPopulation));  
    }     
  return map;      
}
tip_yip
  • 11
  • 2
  • Do you understand what the exception means? Can you explain why you don't think you should be getting this exception, and what you've found in your investigation so far? – ruakh Sep 20 '21 at 02:53
  • 1
    You may find https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ to be helpful. – ruakh Sep 20 '21 at 02:55

1 Answers1

2

If you have no comma in one single line in your file "Assignment1CData.txt" the resulted array "trim" will have only one element at index 0. If this is the case the error is produced when you try to access index 1 in your one element array.

Stefan
  • 164
  • 1
  • 10
  • It’s not that the missing comma caused the exception, as said in the comments, this problem is easy to locate through debug. – zysaaa Sep 20 '21 at 03:21