0

So using the following code:

try (BufferedReader br = new BufferedReader(new FileReader("Program10.txt")))
{
String sCurrentLine;
String[] splits;
            
while ((sCurrentLine = br.readLine()) != null) 
{
splits = sCurrentLine.split("\\s+");
}
}
catch (IOException e) 
{
e.printStackTrace();
}
System.out.println(splits); // prints as null

I've read the file, Program10.txt, by line to get:

[1000  31000  3 Texas, 
1042  12180.06  3 Texas, 
1062  13240.45  2 Texas, 
1200  36000  2 Maryland, 
1327  19800.56  2 Alaska, 
1483  22458.23  7 Texas, ...
]

And I'm hoping to print the entire line when the income (so the second element is greater than average income, which is 5,037) with the following code (***I suspect the problem is with the bolded code):

ArrayList<Household> households = new ArrayList<Household>();
**// This will create new household object
Household household = new Household(
Integer.parseInt(splits[0]), 
Double.parseDouble(splits[1]), 
Integer.parseInt(splits[2]), 
splits[3]);

I'm getting a null Exception in thread "main" java.lang.NullPointerException at Program10.readFile(Program10.java:129) (line 129 corresponds to the code "Integer.parseInt(splits[0]), "

Is there something obvious I'm missing here?

Erin
  • 465
  • 4
  • 11
  • You're throwing out every single array placed into the splits array except the last one, and I don't think that this is what you really want to be doing. – Hovercraft Full Of Eels Nov 24 '20 at 04:21
  • Why not instead print each array ***inside*** the while loop, right after creating each array? – Hovercraft Full Of Eels Nov 24 '20 at 04:22
  • hmmm I'm still getting an error when I place the Integer.parseInt(splits[0]), Double.parseDouble(splits[1]), Integer.parseInt(splits[2]) inside that while loop. What do you mean by throwing out the array? – Erin Nov 24 '20 at 04:27
  • Say, that you're reading 10 lines, as the while loop loops, you assign to splits a new array, and discard the previous *without doing anything with it*, without printing it, storing it, nothing. Only the last array entered is the one that is eventually printed. Again, I don't think that this is what you want to do since it simply makes no sense at all. As for your null issue -- time to fire up your debugger to see what is null, when and then why. – Hovercraft Full Of Eels Nov 24 '20 at 04:31

0 Answers0