【问题标题】:Reading text files, for in while vs while in for (java)读取文本文件,for in while vs while in for (java)
【发布时间】:2014-06-10 09:15:09
【问题描述】:

这是一个非常简单的学校练习代码示例。我让它工作,但我不明白为什么我的第一个想法没有工作。我的第一个想法是双 for 循环中的 while 循环(参见 cmets /* */)。如果我使用这些循环,它会返回一个用零填充的数组(有一个文件 integer.txt,其中包含相同方向的随机数,这不是问题)。

和 sc.hasNextInt() 有关系吗?我真的不明白为什么它以这种方式工作而不是其他方式。

感谢您提前解释。

public static void main(String[] args) throws IOException {
    String filename = "integer.txt";
    FileReader fr = new FileReader(filename);
    Scanner sc = new Scanner(fr);

    int[][] getallen = new int[2][5];

    /*for(int i = 0; i < 2; i++){
        for(int j = 0; j < 5; j++){
            while(sc.hasNextInt()){
                getallen[i][j] = sc.nextInt();
            }
        }
    }*/



    while(sc.hasNextInt()){
        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 5; j++){
                getallen[i][j] = sc.nextInt();
            }
        }
    }

    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 5; j++){
            System.out.print(getallen[i][j] + " ");
        }
        System.out.println();
    }


    System.out.println("Ok.");
    sc.close();
 }

【问题讨论】:

  • 无论您使用此代码尝试什么,您的for 循环都是不必要的。你不需要它们。你只需要玩数组索引
  • 好的,但是我必须以某种方式循环遍历索引,并且练习是将数字放入 2x5 数组中,所以我在这里看不到其他选项..
  • 你可以这样做int i=0,j=0; while(sc.hasNextInt()){ getallen[i][j] = sc.nextInt(); if(j==5) { i++; j=0; } }
  • 写信给我似乎很奇怪...这实际上比 for 循环好吗?当我知道必须填充多少个空格时,我学会了使用 for 循环,并学会了在未知填充数组时使用 while 循环...

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


【解决方案1】:

为什么

   for(int i = 0; i < 2; i++){
        for(int j = 0; j < 5; j++){
            while(sc.hasNextInt()){
                getallen[i][j] = sc.nextInt();
            }
        }
    }

这段代码不起作用?

因为一旦它到达你的 while 循环,它就会一次又一次地覆盖相同的索引值。

【讨论】:

    【解决方案2】:

    在您的 while 循环中,i 和 j 永远不会继续前进,因此在您的 while 循环中,您会不断地覆盖 getallen 中的相同位置。

    只需跟踪代码的作用,它应该是显而易见的。 i 和 j 为 0。然后循环从扫描仪中提取所有内容并将其设置为 getallen[0][0]。然后它耗尽了扫描仪,因此它以包含最后一个扫描仪值的 0,0 继续前进。对于其他每一步(除非扫描仪中有新内容),hasNextInt() 都会返回 false,因此它甚至永远不会执行,并且 getallen[i][j] 不会被修改,这意味着它保持其默认值 0。

    【讨论】:

    • 所以如果我理解正确的话,在第一种情况下,while 循环会遍历文本文件中的所有数字,并且只保存数组中 10 个数字中的最后一个数字?
    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2022-12-27
    相关资源
    最近更新 更多