【问题标题】:Scanner issue with "hasNextInt()"“hasNextInt()”的扫描仪问题
【发布时间】:2014-06-04 01:04:48
【问题描述】:

我有一个文件,每行都有一个不同的整数。例如:

5
4
3
2
1

我正在尝试编写一个程序来运行每个 int,并将该 int 放入一个数组中。到目前为止,我的代码是:

      Scanner sc = new Scanner(args[0]);

      BufferedReader reader = new BufferedReader(new FileReader(args[0]));
      lines = 0;
      while (reader.readLine() != null) lines++;
      reader.close();

      intArray = new int[lines];

      int counter = 0;
      while(sc.hasNextInt()) {
        intArray[counter] =sc.nextInt();
        counter++;
      }

我的程序创建了具有正确数量索引的数组,但它永远不会进入扫描仪的 while 循环。我不知道这是为什么,因为根据page 看起来我有相同的代码。

【问题讨论】:

    标签: java arrays java.util.scanner


    【解决方案1】:

    除非您的文件路径是空格分隔的数字,否则您不会得到任何数字。 Scannerwas scanning the file path(作为String),而不是文件。

    Scanner sc = new Scanner(new FileInputStream(args[0]));
    

    仅供参考,如果您使用List 而不是两次读取文件会更清楚。

    【讨论】:

    • 这就是诀窍,它查看的是字符串而不是文件。完美!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多