从文本文件中取出双打数组

时间:2017-12-07 23:30:05

标签: java arrays

我需要阅读成绩档案并将其输入数组。我似乎无法弄明白。有什么建议。谢谢你的帮助 :) 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();

2 个答案:

答案 0 :(得分:3)

一个。正如@hnefatl所说,你需要在循环中对语句进行分组,

while(<condition>) {
   statement1;
   ...
   statementN;
}

否则只有下一个执行。

while(<condition>) statement1;
...

B中。当你做String line = gradesFile.nextLine();时 如果有文件,那么你从文件获得第一行,扫描器位置在下一行。

因此,在此之后执行gradesFile.hasNextDouble(),Scaner会在下一行中查找double。

如果您想使用nextLine()并且您的双打是&#34;每行一次&#34;你需要在循环中使用它们:

    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()

混合使用
    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();

答案 1 :(得分:1)

您只需扫描文件中的double值并将其存储在数组中,如下所示

Eg:
Select A.id, A.value, B.value
From   (select id, count(*) as value from TableA ...) AS A
join   (select id, sum(field) as value from TableB ...) AS B
on   A.id = B.id
order by A.id 

打印存储在数组中的内容

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();
}