从文本文件读取,然后将值分配给数组

时间:2019-04-02 22:40:04

标签: java arrays file

我的班级项目是提示用户输入文件,他们输入的文件名必须正确,一旦建立文件,文件的第一行就是数组的大小。然后,我必须逐行将每个值分配给数组。

快速笔记**我们尚未了解缓冲的读取器,因此无法使用。我也不能使用ArrayList,也还没有介绍。

问题:如何确保他们输入的文件名正确?到目前为止,我们在课堂上使用while循环进行检查,但我想知道是否有更好的方法。我需要用户输入“ investments.txt”,否则我需要一次又一次地提示他们。同样,对改进现有代码的任何观点都表示赞赏,我对此很陌生。

到目前为止的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Prog07_InvestmentManager {

    public static void main(String[] args) {

    Scanner in = new Scanner(System.in);    

    System.out.println("Please enter the file name to import. Example: Investments.txt."); //prompt user
    File file = new File(in.nextLine());

    try {
        Scanner inFile = new Scanner(new FileReader("investments.txt"));
        double min = Integer.MAX_VALUE;
        double max = 0;
        double mean = 0;
        int num = inFile.nextInt();
        inFile.nextLine();

        double line = 0;
        int sum = 0;
        int count = 0;

        while (inFile.hasNextLine()) {

            line=inFile.nextDouble();
            sum+=line;
            count++;

            if(line>max)
                max=line;

            if(line<min)
                min=line;
        }
        mean = (sum/count);
        System.out.println("Max: "+max);
        System.out.println("Min: "+min);
        System.out.println("Mean: "+mean);
        System.out.println();
    } catch (FileNotFoundException e1) {

    }
    if (in.hasNextDouble()) {

    double[] values = new double [(int) in.nextDouble()];

    }

    try {
        Scanner inputFile = new Scanner(file);

        double[] arr = new double[(int) in.nextDouble()];

        for (int i = 0; in.hasNextDouble(); i++) {
            arr[i] = in.nextDouble();
        }

    } catch (FileNotFoundException e) {
        file = new File("investments.txt");
        System.out.print("File not found.\nPlease enter the correct path if needed.");
        file = new File(in.nextLine());                 
        }
    in.close();
    }
}

2 个答案:

答案 0 :(得分:1)

第一个建议是使用List <>接口,而不是原始数组

List<Double> value = new ArrayList<>();

1&2通过对列表进行排序可以轻松完成,第一个和最后一个元素分别是min和max。

在那之后,这只是一个问题,或者使用foreach循环来查找其他值

for (Double element : value) {
   // do math
}

答案 1 :(得分:1)

因此您的代码有几个问题:

  1. 输入文件名后,现在应该使用“ in”扫描仪完成操作。您正试图开始从System.in中读取数据,除非您手动输入所有数据,否则这将导致程序挂起。

  2. 您永远不会用System.in中的String覆盖原始文件变量。您甚至不必一定要使用默认值开始。 只需删除File file = new File("investments");String fileName = in.nextLine();

    然后在提示后添加File file = new File(in.nextLine());

  3. 在try / catch之外的while循环也是有问题的,可以完全删除。同样,您尝试从System.in中读取所有数据。

  4. 您不匹配hasNextDouble()和.nextLine()。这适用于您当前的设置,因为每个数字都位于新行中,但通常应使用相同的数据类型。

  5. 通常,您可以使用以下命令从文件中读取双精度数组:

   Scanner scanner = new Scanner(file);
   double arr = new double[scanner.nextInt()];

   for(int i = 0; scanner.hasNextDouble(); i++) {
       arr[i] = scanner.nextDouble();
   }
   scanner.close();

相关问题