Whats wrong with this code?

Started by
3 comments, last by The Orange Peanut 18 years, 4 months ago
It's giving me a NumberFormatException: null when I run my test program (which does nothing but construct an object of StandardDeviation.) integers is passed as the pathname argument to the construct, and the file integers.dat does exist in the path. I think I've initialized everything. Also, each line seemed to work when it wasn't as complex. Obviously I did something to mess it up when I tried making it all work together. Any insight?

import java.io.*;

public class StandardDeviation
{
	int[] numbers; //stores the numbers in the file into an array
	int numberOfIntegers;   //counts the number of integers read
	int sum;
	float mean;
	
	public StandardDeviation(String pathname) throws IOException
	{
		sum = 0;
		mean = 0;
		numberOfIntegers = 0;
		numbers = new int[25];  //assumes no more than 25 numbers in file
		
		readFile(pathname);
		
	}
	
	private void readFile(String pathname) throws IOException
	{
		BufferedReader infile = new BufferedReader(new FileReader(pathname + ".dat"));
		int numberRead = 0;
		
		do
		{
			numberRead = Integer.parseInt(infile.readLine());
			
			sum += numberRead;
			numbers[numberOfIntegers] = numberRead;
			numberOfIntegers++;
			
		}while(infile.readLine() != null);
	}
	
}

Dat is off da hizzle fo shizzle dizzle
Advertisement
Given the exception, I would imagine the problem is with the Integer.parseInt, though I can't be sure.

Try putting some try/catch problems in strategic places to find out on exactly what line the error is.

Cheers,
--Brian
You're calling BufferedReader.readLine() twice - the first time you're checking for the exit condition but the second time you're not. When it hits the last line - and infile.readLine() isn't null, you're trying to parse the next non-existant line. Try saving the line into a String variable and operating on that instead :
...String line = null;while( ( line = infile.readLine() ) != null ){   numberRead = Integer.parseInt( line );}...


<edit :: Nairb is correct. You'll need to wrap your readline call in a try/catch block, as BufferedReader.readLine() will hurl an java.io.IOException if anything bad happens.
- stormrunner
int numbers[]; instead of int [] numbers; maybe?

NBA2K, Madden, Maneater, Killing Floor, Sims http://www.pawlowskipinball.com/pinballeternal

Thanks for the help. We did this at the beginning of the semester, I guess that is what I get for not practicing.
Dat is off da hizzle fo shizzle dizzle

This topic is closed to new replies.

Advertisement