import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\HIM\\IdeaProjects\\File Tutorial\\src\\quad.txt");
Scanner scanner = new Scanner(file);
double a , b, c;
double[] arr = new double[3];
for(int i = 0; i < arr.length; i++) {
while (scanner.hasNextLine()) {
arr[i] = scanner.nextInt();
System.out.println(arr[i]);
}
}
a = arr[0];
System.out.println(a);
b = arr[1];
System.out.println(b);
c = arr[2];
System.out.println(c);
} catch (Exception e){
System.out.println("Not Found");
}
}
}
我使用了这段代码,但是从将值 2、3、4 传输到数组的循环中,它已成功读取,但我尝试将这些数组值初始化为 a、b、c,但它只读取最后一个值并将其分配给 a。
最佳答案
您没有说您的输入文件是什么样的,因此很难准确地告诉您出了什么问题,但我怀疑问题是您在循环中使用了 hasNextLine
,但在阅读时使用了 nextInt
。这不会按照您期望的输入方式运行,例如:
1 2 3
请注意,只有一行,因此 hasNextLine
将返回 false,因为虽然有多个整数,但只有一行。
您可能想要的是 Scanner#hasNextInt
此外,这个逻辑可能不正确:
for(int i = 0; i < arr.length; i++) {
while (scanner.hasNextLine()) {
arr[i] = scanner.nextInt();
System.out.println(arr[i]);
}
当扫描仪移动到下一个 token 时,您无法返回。因此您只能读取一次,而无需创建新的扫描仪。
您可能想要的是以下内容:
int i = 0;
while (scanner.hasNextInt()) {
arr[i] = scanner.nextInt();
System.out.println(arr[i]);
i++;
}
这将通过扫描仪一次并正确填充您的值。
关于java - 有没有办法从文件中读取值并初始化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470673/