Array Printf问题

时间:2014-06-09 09:08:50

标签: java arrays

我正在研究应该列出数组中数值的简单程序;某种方式。这就是我希望输出看起来像:

Printing Array:
 1    2    3    4    5    6    7    8    9   10
11   12   13   14   15   16   17   18   19   20
21   22

必须如上所示排列,行必须只包含10个数字。 我似乎已经正确地格式化了所有内容,但我的输出看起来并不像那样。

这是我得到的:

Printing Array:
 1
 2    3    4    5    6    7    8    9    10    11
12   13   14   15   16   17   18   19    20    21
22

我不确定我做错了什么,但这是我的代码:

//disregard the name 'Juice', I like to give my programs weird names

public class Juice 
{
  public static void main(String[] args) 
  {
      //sets up the array
      int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22};

      //title
      System.out.println("Printing Array: ");

      //counting the elements
      for (int i = 0; i < numbers.length; i++)
          {
              //prints each element value with 4 spaces in between
              System.out.printf("%4d", numbers[i]);

              //once line reaches ten values; print new line
              if (i % 10 == 0)
              {
                System.out.printf("\n");
              }
          }
   }
}

4 个答案:

答案 0 :(得分:4)

if ((i+1) % 10 == 0)
 {
    System.out.printf("\n");
 }

答案 1 :(得分:3)

您的代码按照您的要求执行。

在第一个循环中,i=0,但i % 10 == 0也是如此,因此它会打印新行。 您可以使用许多不同的方法来解决此问题,但最简单的方法是将此条件替换为(i+1) % 10 == 0i % 10 == 9

答案 2 :(得分:1)

你几乎做到了

public class Juice 
{
  public static void main(String[] args) 
  {
      //sets up the array
      int[] numbers = {1,2,3,4,5,6,7,8,9,10,12,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32};

      //title
      System.out.println("Printing Array: ");

      //counting the elements
      for (int i = 0; i < numbers.length; i++)
          {
              //prints each element value with 4 spaces in between
              System.out.printf("%4d", numbers[i]);

              //once line reaches ten values; print new line
              if (i % 10 == 9)
              {
                System.out.printf("\n");
              }
          }
   }
}

我已将条件修改为if (i % 10 == 9)

<强>输出

Printing Array: 
   1   2   3   4   5   6   7   8   9  10
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32

答案 3 :(得分:0)

或者,为了避免数组元素的索引与使用foreach循环的元素计数切换之间的混淆。

   //counting the elements
    int i = 1;
    for (int number : numbers) {
      //prints each element value with 4 spaces in between
      System.out.printf("%4d", number);

      //once line reaches ten values; print new line
      if (i % 10 == 0) {
        System.out.println();
      }

      i++;
    }