问题
I have a question on how to store output from a file into an array. In my case, I am trying to store all the date in a file into an array. For the way that I did it, the compiler complains "not a statement". How can I fix this? Any help will be greatly appreciated. Below is my code (the line of error is preceded by backslashes):
double token[] = new double[9];
File filename = new File("/Users/timothylee/gravity1.txt");
Scanner inFile = new Scanner(filename);
while(inFile.hasNext()){
//////////////// token[] = inFile.nextDouble();
System.out.println(token);
}
inFile.close();
If needed, here is the file:
gravity1.txt:
3.70
8.87
9.79
3.70
24.78
10.44
8.86
11.13
0.61
回答1:
double token[] = new double[9];
int i = 0;
while(inFile.hasNext()){
token[i] = inFile.nextDouble();
System.out.println(token);
i++;
}
inFile.close();
This is assuming the file only has 9 lines.
回答2:
ArrayList<Double> token = new ArrayList<Double>();
File filename = new File("/Users/timothylee/gravity1.txt");
Scanner inFile = new Scanner(filename);
while(inFile.hasNext()){
token.add(inFile.nextDouble());
}
inFile.close();
System.out.println(Arrays.toString(token));
Just use an ArrayList, dont make your life harder as it is. ;) This also makes it way more flexible, as it doesnt matter how many data/lines are in your file.
回答3:
You are not assigning anything to your token array, which is why you are getting the "not a statement" error. You need to tell Java where to put the next double like this:
double token[] = new double[9];
File filename = new File("/Users/timothylee/gravity1.txt");
Scanner inFile = new Scanner(filename);
int i = 0;
while(inFile.hasNext()){
token[i] = inFile.nextDouble();
System.out.println(token);
i++;
}
inFile.close();
回答4:
This would be simpler in Java 8 with map. Here is the Java 7 version:
File filename = new File("/Users/timothylee/gravity1.txt");
List<Double> doubleList = new ArrayList<Double>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
doubleList.add(Double.parseDouble(line))
}
}
double[] doubles = new double[doubleList.size()];
for (int i = 0; i < doubleList.size(); i++) {
doubles[i] = doubleList.get(i);
}
来源:https://stackoverflow.com/questions/20549272/java-storing-output-from-file-into-an-array