【问题标题】:Java: Is it possible to make line break x times inside for loop?Java:是否可以在 for 循环中进行 x 次换行?
【发布时间】:2013-08-13 09:22:32
【问题描述】:

我尝试在 Google 和 StackOverflow 上搜索我的问题,但没有找到任何答案。

我制作了一个数组,其中大小和值都是随机生成的。当数组值已打印 20 次时,我想换行,但不打印其余值总是换行。

这是我的代码:

public static void catArr() {

    Random rändöm = new Random();
    int size = rändöm.nextInt(100);

    int[] arr = new int[size];

    for (int i = 0; i < size; i++) {

        arr[i] = rändöm.nextInt(100);
    }

    Arrays.sort(arr);

    for (int i = 0; i < size; i++) {

        System.out.print(" " + arr[i]);
        if (i > 20)
            System.out.println(); //How to do this only once?
        else if (i > 40)
            System.out.println(); //Same here?
    }

}

这是生成的输出之一:

 3 8 10 25 30 31 34 38 46 50 55 59 62 66 67 68 68 68 72 76 76 81
 82
 83
 84
 86
 91
 92
 93
 94
 94
 97

我认为解决这个问题的一种方法是使用二维数组,但我想知道是否有另一种方法。

感谢 Patric,我得到了想要的结果:

0   2   3   7   7   9   11  14  14  16  18  19  24  25  26  28  28  30  30  31  
31  33  33  34  41  41  41  42  43  44  45  46  51  51  52  53  59  60  61  62  
62  62  63  65  65  67  67  68  69  70  74  74  76  78  82  83  84  84  87  88  
89  93  93  94  94  94  95

【问题讨论】:

  • “if (i==20)”不符合您的要求吗?它只打印一次。如果你想要每 20 次尝试“if (i%20==0)”,它会说“当 i 可以被 20 整除”

标签: java arrays for-loop line-breaks


【解决方案1】:

尝试使用

if ( ( i % 20 ) == 0 ){
    System.out.println();
}

如果我除以 20 没有余数,则打印一个新行!

【讨论】:

  • 这几乎是正确的!我只是不明白为什么我得到第一个值然后换行。像这样:code 4 5 6 10 14 18 21 28 28 29 32 36 42 42 47 55 65 66 69 71 71 72 77 91 95 98 99
  • 因为如果 i = 0 则没有余数 - 试试 if ( ( i % 20 == 0 ) && i > 0 ) {
  • 哦,现在我解决了,我必须在 for 循环中将 int i = 1 更改为 0。谢谢! :)
【解决方案2】:

也许

if (i % 20==0) 

可以解决你的 else if 问题。

【讨论】:

    【解决方案3】:

    使用(++i % 20) == 0 并从循环中删除i++pre-increment 避免第一个不需要的换行符。

    【讨论】:

      【解决方案4】:

      从字面上看,这会做你想要的:

          if (i == 20)
              System.out.println();
          else if (i == 40)
              System.out.println();
      

      但我有一种感觉,您实际上想在 20th、40th、60th 等之后添加换行符。

          if (i % 20 == 0) 
              System.out.println();
      

      如果你想在最后只输出一个换行符,那么你需要这样的东西:

          for (int i = 0; i < size; i++) {
              if (i > 1 && i % 20 == 1) {
                  System.out.println();
              System.out.print(" " + arr[i]);
          }
          System.out.println();
      

      【讨论】:

        【解决方案5】:

        您可以为您的系统输出使用布尔值。

        boolean myBoolean = true;
        if(myBoolean){
            //print
            myBoolean = false; //set boolean to false.
        }
        

        另一方面,在我的偏好中,我仍然坚持使用整数标记。

        int isTrue = 1;
        if(isTrue == 1){
            //print
            isTrue = 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-21
          相关资源
          最近更新 更多