扫描文件中的双精度数组|爪哇

我正在尝试扫描具有双精度数组的文件。我正在使用下面的代码,但每个条目仅输出0.0。为什么会这样,我该如何解决?

Scanner scanner = new Scanner("file.txt");
double[] array = new double[256 * 256];
    for (int i = 0; i < array.length; i++) {
        if (scanner.hasNextDouble()) {
            array[i] = scanner.nextDouble();
        }
    }
System.out.println(array[0]);

我正在扫描的文件的示例为[0.22131145、0.22131145、0.22131145、0.22841525、0.22841525,....]

评论
  • 伊~小夏
    伊~小夏 回复

    您的代码存在三个问题:

    1. Blocker: Scanner expects a File object but you haven't used it in this way. You need to use the following syntax:

      Scanner scanner = new Scanner(new File("file.txt"));
      
    2. Performance: You can improve the performance of your program by including scanner.hasNextDouble() in the condition which checks the value of i, as shown below:

      for (int i = 0; i < array.length && scanner.hasNextDouble(); i++) {
          array[i] = scanner.nextDouble();
      }
      

      This will terminate the loop as soon as scanner.hasNextDouble() returns true; otherwise, the loop in your code will continue to run until i < array.length evaluates to false irrespective of the value returned by scanner.hasNextDouble().

    3. Resource leak: You have not closed the Scanner object. Do it as follows after the loop finishes:

      scanner.close();
      
  • 小梨涡
    小梨涡 回复

    The main issue is with the instantiation of the Scanner object. In this case you need to pass a File object into it, not just a string, and make sure you specify the correct file path. Refer to the official documentation for advice.

    其次,您需要使用while循环。 if语句仅执行一次,但是您希望Scanner在文件中有信息的同时继续查找。

    Thirdly, don't use an array for storing the values. It's too risky because you need to know the size of the array beforehand, meaning that you would need to loop twice, which would be inefficient, or you are hard coding, as you are doing here. If someone were to add or remove values from the file, you will get unexpected results. Rather use a dynamic data structure such as a List.

    public static void main(String[] args) throws FileNotFoundException {
        String filepath = "file.txt";
        Scanner scanner = new Scanner(new File(filepath));
        List<Double> list = new ArrayList<>();
    
        while (scanner.hasNextDouble()) {
            list.add(Double.valueOf(scanner.next()));
        }
    
        System.out.println(list.get(0));
    }