简体   繁体   English

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

[英]Scan array of doubles in a file | Java

I was trying to scan a file that has an array of doubles.我试图扫描一个包含双精度数组的文件。 I'm using the code below but it's only outputting 0.0 for every entry.我正在使用下面的代码,但它只为每个条目输出0.0 Why is this and how can I fix it?为什么会这样,我该如何解决?

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

An example of the file I'm scanning is我正在扫描的文件的一个示例是

0.22131145 0.22131145 0.22131145 0.22841525 0.22841525 ...

The main issue is with the instantiation of the Scanner object.主要问题在于扫描器 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.在这种情况下,您需要将File object 传递给它,而不仅仅是一个字符串,并确保指定正确的文件路径。 Refer to the official documentation for advice.请参阅官方文档以获取建议。

Secondly, you need to use a while-loop.其次,您需要使用while循环。 An if-statement will execute only once, but you would want the Scanner to continue looking whilst there is info inside the file. if 语句只会执行一次,但您希望扫描程序在文件中有信息时继续查找。

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 .而是使用动态数据结构,例如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()));
    }

    scanner.close();
    System.out.println(list.get(0));
}

There are four problems with your code:您的代码有四个问题:

  1. Blocker : Scanner expects a File object but you haven't used it in this way.阻止程序: 扫描程序需要文件object,但您没有以这种方式使用它。 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:性能:您可以通过在检查i值的条件中包含scanner.hasNextDouble()来提高程序的性能,如下所示:

     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 false ;一旦scanner.hasNextDouble()返回false ,这将终止循环; 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() .否则,无论scanner.hasNextDouble()返回的值如何,代码中的循环都将继续运行,直到i < array.length评估为false

  3. Resource leak : You have not closed the Scanner object.资源泄漏:您尚未关闭Scanner object。 Put the following line after the loop finishes:在循环结束后添加以下行:

     scanner.close();
  4. Missed functionality : You haven't printed the complete array.缺少的功能:您还没有打印完整的数组。 Your statement, System.out.println(array[0]) will print only the first element in the array.您的语句System.out.println(array[0])将仅打印数组中的第一个元素。 Change it as follows to print the complete array:将其更改如下以打印完整的数组:

     System.out.println(Arrays.toString(array));

    Given below the code incorporating all the above-mentioned comments:下面给出了包含所有上述注释的代码:

     import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("file.txt")); double[] array = new double[256 * 256]; for (int i = 0; i < array.length && scanner.hasNextDouble(); i++) { array[i] = scanner.nextDouble(); } scanner.close(); System.out.println(Arrays.toString(array)); } }
  5. Memory utilization : You have used a fixed-sized array which is fine if the number of elements to be stored is equal to the size of the array. Memory 利用率:您使用了一个固定大小的数组,如果要存储的元素数等于数组的大小,这很好。 However, if it is not the case (ie if the number of elements to be stored can be less than or more than the specified size), you should use a Collection eg an ArrayList which is a kind of dynamic array.但是,如果不是这种情况(即,如果要存储的元素数量可以小于或大于指定大小),则应使用Collection ,例如ArrayList ,它是一种动态数组。 This will help you in many ways: (a) You will save memory if the number of elements to be stored is less than the specified size (b) You do not need to change your code in order to increase the size of the array when you need to store more elements than you have already specified (c) The Collection provides with a rich API to deal with elements.这将在很多方面帮助您: (a) 如果要存储的元素数量小于指定大小,您将保存 memory (b) 您不需要更改代码以增加数组的大小您需要存储比您已经指定的更多的元素 (c) Collection提供了丰富的 API 来处理元素。 By leveraging this API, your code can be crisp, more performant, maitainable etc.通过利用这个 API,您的代码可以更清晰、更高效、更易于维护等。

    Given below the code incorporating the 5th point:下面给出了包含第 5 点的代码:

     import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("file.txt")); List<Double> list = new ArrayList<>(); while (scanner.hasNextDouble()) { list.add(scanner.nextDouble()); } scanner.close(); System.out.println(list); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM