我正在尝试扫描具有双精度数组的文件。我正在使用下面的代码,但每个条目仅输出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,....]
您的代码存在三个问题:
Blocker: Scanner expects a File object but you haven't used it in this way. You need to use the following syntax:
Performance: You can improve the performance of your program by including
scanner.hasNextDouble()
in the condition which checks the value ofi
, as shown below:This will terminate the loop as soon as
scanner.hasNextDouble()
returnstrue
; otherwise, the loop in your code will continue to run untili < array.length
evaluates tofalse
irrespective of the value returned byscanner.hasNextDouble()
.Resource leak: You have not closed the
Scanner
object. Do it as follows after the loop finishes: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
.