[英]How do I get Java to read a list of numbers from a text?
如何获取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);
}
}
输出:
385
385
385
385
385
385
385
385
385
就像您在for循环的每个迭代中初始化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
(可以使用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.