[英]Making an array out of doubles from a text file
我需要阅读成绩文件并将其输入数组。 我似乎无法弄清楚。 有什么建议么。 感谢您的帮助:) grades.txt文件如下所示:
90.0
71.5
87.9
95.0
98.1
码:
File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();
//create array
double[] array = new double[12];
//variable to increment
int u = 0;
//loop to put data into array
while(gradesFile.hasNextDouble())
array[u] = gradesFile.nextDouble();
u += 1;
gradesFile.close();
答:正如@hnefatl所说,您需要在循环中对语句进行分组,
while(<condition>) {
statement1;
...
statementN;
}
否则,只有下一个执行。
while(<condition>) statement1;
...
B.当你做String line = gradesFile.nextLine();
您从文件获得了完整的第一行,并且如果有的话,扫描仪位置在下一行。
因此,在gradesFile.hasNextDouble()
之后执行gradesFile.hasNextDouble()
, gradesFile.hasNextDouble()
在下一行中查找double。
如果您想使用nextLine()
并且您的双打是“单行”,则需要以如下方式循环使用它们:
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextLine()) {
String line = gradesFile.nextLine();
array[u] = Double.parseDouble(line);
u += 1;
}
gradesFile.close();
或者如果您想使用nextDouble()
, nextLine()
其与nextLine()
混合使用
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextDouble()) {
array[u] = gradesFile.nextDouble();
u++;
}
gradesFile.close();
您可以简单地扫描文件中的double值并将其存储在数组中,如下所示
Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;
try {
scan = new Scanner(file);
//Scan while the file has next double value
while(scan.hasNextDouble())
{
//Save the double value read from text file and store to array
array[i] = scan.nextDouble();
i++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
打印数组中存储的内容
for(int y = 0; y < array.length;y++)
{
System.out.println(array[y]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.