【问题标题】:For Loop ending after 1 rotation when using Scanner使用扫描仪时循环在 1 次旋转后结束
【发布时间】:2013-12-26 01:29:23
【问题描述】:

我目前正在开发一个程序,它检查文本文档中的每一行,并对其进行相同的修改。但是,for 循环仅循环一次,而不是所需的 5 次。以下是不工作的代码部分。

//I think this part is correct but I decided to include it just in case.
Scanner infile = null;
try {
    infile = new Scanner(new File("solution.txt"));
} catch(FileNotFoundException e) {
    System.out.println(e);
    System.exit(0);
}

for(int i = 0; i < 5; i++);
{
    s = infile.nextLine();
    System.out.println(s);
    System.out.println("LOOP"); //Just a debug test
}
infile.close();

这段代码的输出如下:

define 88 as INT
LOOP

应该是这样的:

define 88 as INT
LOOP
define 89 as INT
LOOP
define 90 as INT
LOOP
define 91 as INT
LOOP
define 92 as INT
LOOP

【问题讨论】:

    标签: java for-loop input java.util.scanner


    【解决方案1】:

    你需要在for循环结束时去掉;

    你使用的for循环代码

        for(int i = 0; i < 5; i++);
        {
            s = infile.nextLine();
            System.out.println(s);
            System.out.println("LOOP"); //Test system out
        }
    

    等于下面的代码:

        for (int i = 0; i < 5; i++) {
    
        }
        s = infile.nextLine();
        System.out.println(s);
        System.out.println("LOOP"); // Test system out
    

    这就是为什么只从纯文本文件中读取第一行内容的原因。

    你最好使用infile.hasNext()来检查是否有内容。然后阅读它。喜欢

        while (infile.hasNext()) {
            s = infile.nextLine();
            System.out.println(s);
            System.out.println("LOOP"); // Test system out
        }
    

    【讨论】:

      【解决方案2】:

      去掉分号:

      for(int i = 0; i < 5; i++);
      

      is valid 之后的代码本身,因此单独运行一次。

      {
          s = infile.nextLine();
          System.out.println(s);
          System.out.println("LOOP"); //Test system out
      }
      

      【讨论】:

      • @Ripread 如果您认为解决了您的问题,请接受答案。
      • 别担心,我会的。不过仍然需要等待 5 分钟。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 2016-02-06
      • 2012-09-27
      • 2016-01-26
      相关资源
      最近更新 更多