Populating multiple arrays with a File.
I am trying to populate multiple arrays with data from a file. I have created 7 arrays which correspond the files 7 lists.
Here is an example of the rows:
Quote:
GHCND:USW00014764 2011/01/01 0 0 127 122 -17
GHCND:USW00014764 2011/01/02 5 0 102 67 28
When I run my program I get the following output:
Quote:
null null 0.0 0.0 0.0 0.0 0.0
null null 0.0 0.0 0.0 0.0 0.0
Obviously my arrays are not being populated, but I don't know why. I will post my code below. Any help would be awesome!
Code :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WeatherArray {
public static void main(String[] args)
throws FileNotFoundException{
int counter = 0;
int rows = 0;
Scanner input = new Scanner(new File("PortlandWeather2011.txt"));
String head1 = input.nextLine();
String head2 = input.nextLine();
System.out.println(head1);
System.out.println(head2);
while(input.hasNext()){
String counts = input.nextLine();
rows++;
}
// Create Arrays
String[] station = new String[rows];
String[] date = new String[rows];
double[] prcp = new double[rows];
double[] snow = new double[rows];
double[] snwd = new double[rows];
double[] tmax = new double[rows];
double[] tmin = new double[rows];
// Populate Arrays
while(input.hasNextLine()){
station[counter] = input.next();
date[counter] = input.next();
prcp[counter] = input.nextDouble();
snow[counter] = input.nextDouble();
snwd[counter] = input.nextDouble();
tmax[counter] = input.nextDouble();
tmin[counter] = input.nextDouble();
counter++;
}
// Print Arrays
for(int i = 0; i <= rows - 1; i++){
System.out.printf("%17s %10s %8.1f %8s %8s %8.1f %8.1f \n", station[i], date[i], prcp[i], snow[i], snwd[i],
tmax[i], tmin[i]);
}
}
}
Re: Populating multiple arrays with a File.
It appears that you're trying to read through the file twice, the first time to get the count and the second time to get the data. If so, then you will need to close the Scanner and then re-initialize it with the File between reads. You're also using the Scanner in an unsafe manner. Myself, if I check input.hasNextLine() then I follow that with input.nextLine(). Each nextXXX() should be paired with a hasNextXXX().
Re: Populating multiple arrays with a File.
[/COLOR]Thank you for your help again! I was able to fix my problem by closing the scanner, and reopening it again like you said. I am also going to take your advice about the .nextLine() and .hasNextLine()
Re: Populating multiple arrays with a File.