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

时间:2018-11-05 22:36:28

标签: java

如何获取Java代码以从文本文件中的数字列表中读取下一个数字。我的输出多次重复第一个数字,该如何解决?

script

输出:

385

385

385

385

385

385

385

385

385

2 个答案:

答案 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)

  1. Scanner初始化为循环
  2. 赶上FileNotFoundException
  3. 组合声明和初始化变量(在这种情况下)
  4. 为变量使用明确的 camelCase 标识符
  5. 避免使用l(小写的L)作为变量标识符。在许多字体中,l(小写L)和1(数字1)看起来很相似。这可能会导致将来由于错别字而引起的错误。
  6. 最后关闭您的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();
}