This is my first time dealing with file I/O and need help figuring out the best way to read in data and store it for further manipulation. I have a file that contains an individual's salary, and 3 product ratings on each line, such as: 75000 01 05 09
What is the best way to store this data? I know how to use BufferedReader and how to tokenize each integer. I must write this program to deal with any number of lines in a file. There are three income brackets, and I must also be able to perform the following calculations:
a) For each income bracket, the average rating for each product
b) The number of persons in Income Bracket $50000-74000 that rates all three products with a score of 5 or higher.
c) The average rating for Product 2 by persons who rated Product 1 lower than Prodcut 3.
Thus far, I've written the following code to open the file and perform 2 reads to get the total number of lines (individuals) and the total number of inidividuals in each income bracket. It compiles, but I get a null pointed exception at StringTokenizer, for some reason.
Please help! Do I need to take lines in as arrays? (tried this, but don't understand how to get at individual data) Do I need to somehow create objects for each person (if so, how?). My reference text covers this area poorly. Thanks for all help.
import java.io.*;
import java.util.*;
public class Product_Survey
{
public static void main(String [] args)
{
int lineCount = 0;
int inc1total = 0;
int inc2total = 0;
int inc3total = 0;
String name = null;
System.out.println("Please enter income and product info file name: ");
Scanner keyboard = new Scanner(System.in);
name = keyboard.next();
File fileObject = new File(name);
while ((! fileObject.exists()) || ( ! fileObject.canRead()))
{
if( ! fileObject.exists())
{
System.out.println("No such file");
}
else
{
System.out.println("That file is not readable.");
}
System.out.println("Enter file name again:");
name = keyboard.next();
fileObject = new File(name);
}
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(name));
String trash = "No trash yet";
while (trash != null)
{
trash = inputStream.readLine();
lineCount++;
}
inputStream.close();
}
catch(IOException e)
{
System.out.println("Problem reading from file.");
}
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(name));
String trash = "No trash yet";
while (trash != null)
{
trash = inputStream.readLine();
StringTokenizer st = new StringTokenizer(trash);
int income = Integer.parseInt(st.nextToken());
if(income<50000)
{
inc1total++;
}
else if(income<75000)
{
inc2total++;
}
else if(income<100000)
{
inc3total++;
}
}
inputStream.close();
}
catch(IOException e)
{
System.out.println("Problem reading from file.");
}
}
}