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

问题描述 投票:1回答:2

如何让我的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

java
2个回答
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);
    }

0
投票
  1. Scanner初始化为循环
  2. 抓住FileNotFoundException
  3. 结合变量的声明和初始化(在这种特殊情况下)
  4. 为变量使用明确的camelCase标识符
  5. 避免使用l(小写L)作为变量标识符。在许多字体中,l(小写L)和1(数字1)看起来相似。这可能会导致拼写错误导致的未来错误。
  6. 最后关闭你的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();
}
© www.soinside.com 2019 - 2024. All rights reserved.