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);
}
}
Whats wrong with this code?
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?
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
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 :
<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.
...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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement