如何让我的Java代码从文本文件中的数字列表中读取下一个数字。我的输出多次重复第一个数字,我该如何解决这个问题?
public static void main(String[] args) throws Exception {
for (int l = 0; l < 9; l++) {
java.io.File myfile;
String mypath;
mypath = "/Users/tonyg/Downloads";
myfile = new java.io.File(mypath + "/file.txt");
Scanner myinfile = new Scanner(myfile);
int val1;
val1 = myinfile.nextInt();
System.out.println(val1);
}
}
OUTPUT:
385
385
385
385
385
385
385
385
385
看起来您只需在循环之前初始化,就可以在for循环的每次迭代中初始化Scanner,您的问题应该得到解决。使用该资源后,这也是close the Scanner的最佳实践
public static void main(String[] args) throws Exception {
java.io.File myfile;
String mypath;
mypath = "/Users/tonyg/Downloads";
myfile = new java.io.File(mypath + "/file.txt");
Scanner myinfile = new Scanner(myfile);
for (int l = 0; l < 9; l++) {
int val1;
val1 = myinfile.nextInt();
System.out.println(val1);
}
Scanner
初始化为循环FileNotFoundException
l
(小写L
)作为变量标识符。在许多字体中,l
(小写L
)和1
(数字1)看起来相似。这可能会导致拼写错误导致的未来错误。Scanner
(#1,#2和#6可以通过使用try-with-resources
实现)
String dirPath = "/Users/tonyg/Downloads";
String filePath = dirPath + "/file.txt";
int count = 9;
try(Scanner scanner = new Scanner(new File(filePath))){
for (int i = 0; i < count; i++) {
int value = scanner.nextInt();
System.out.println(value);
}
} catch (FileNotFoundException e){
// Print stack-trace or do something else
e.printStackTrace();
}