如何获取Java代码以从文本文件中的数字列表中读取下一个数字。我的输出多次重复第一个数字,该如何解决?
script
输出:
385
385
385
385
385
385
385
385
385
答案 0 :(得分:0)
看起来就像您在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);
}
答案 1 :(得分:0)
Scanner
初始化为循环FileNotFoundException
l
(小写的L
)作为变量标识符。在许多字体中,l
(小写L
)和1
(数字1)看起来很相似。这可能会导致将来由于错别字而引起的错误。 Scanner
(可以使用try-with-resources
来实现#1,#2和#6)
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();
}