gpt4 book ai didi

java - 如何让 Java 从文本中读取数字列表?

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:56 25 4
gpt4 key购买 nike

如何让我的 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 循环的每次迭代中初始化扫描仪,您的问题应该得到解决。最佳实践也是 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);
}

关于java - 如何让 Java 从文本中读取数字列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com