【问题标题】:Making an array out of doubles from a text file从文本文件中制作双精度数组
【发布时间】:2017-12-07 23:30:04
【问题描述】:

我需要读取一个成绩文件并将它们输入到一个数组中。我似乎无法弄清楚。有什么建议么。谢谢你的帮助 :) 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();

【问题讨论】:

  • 你需要 {} 来包围你的 while 循环体...
  • @hnefatl 您应该写下该评论作为答案!然后其他人可以看到解决方案,而您的回答将得到认可。
  • (功能性)for loop without braces in java 的副本。
  • @NileHorse 您需要编辑您的答案以提供minimal reproducible example,准确描述您提供的输入和期望的输出。
  • @NileHorse 如果您能向我们展示“grades.txt”文件的至少一部分,将会有所帮助。

标签: java arrays


【解决方案1】:

A.正如@hnefatl 所说,您需要在循环中对语句进行分组,

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

否则只执行下一个。

while(<condition>) statement1;
...

B.当你做了String line = gradesFile.nextLine(); 你从文件中获得了完整的第一行,如果有的话,扫描仪的位置在下一行。

因此,在此之后执行gradesFile.hasNextDouble(),Scaner 会在下一行查找 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() 混合使用

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

【讨论】:

    【解决方案2】:

    您可以简单地扫描文件中的双精度值并将其存储在数组中,如下所示

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

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多