[英]How do I get Java to read a list of numbers from a text?
How do I get my Java code to read the next number from a list of numbers in a text file. 如何获取Java代码以从文本文件中的数字列表中读取下一个数字。 My output repeats the first number multiple times, how do I fix this? 我的输出多次重复第一个数字,如何解决这个问题?
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 385
385 385
385 385
385 385
385 385
It looks like your initializing the Scanner on every iterations of the for loop by simply initializing before the loop, your issue should be resolved. 就像您在for循环的每个迭代中初始化Scanner一样,只需在循环之前进行初始化即可解决您的问题。 It's also best practice to close the Scanner after using the resource 最好的做法是在使用资源后关闭扫描仪
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
out of loop 循环初始化Scanner
FileNotFoundException
捕获FileNotFoundException
l
(lowercase L
) as a variable identifier. 避免使用l
(小写L
)作为变量标识符。 In many fonts l
(lowercase L
) and 1
(digit one) look similar. 在许多字体中, l
(小写L
)和1
(数字1)看起来很相似。 This may lead to future bugs caused by typos. 这可能会导致将来由于错别字而引起的错误。 Scanner
in the end 最后关闭Scanner
(#1, #2 and #6 can be achieved by using try-with-resources
) (可以使用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.