Sign in to follow this  

Whats wrong with this code?

This topic is 4391 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
	}
	
}

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4391 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this