猿问

如何将数组输出格式化为5个块空间和下一行的其他一半?

所以基本上,如果输入是1,我需要在我的数组中打印12个给定的数字,如果输入是
2,我需要打印随机数。格式应如下所示,一行8,块间距为5,底部为4。

1 2 3 4 5 6 7 8

9 10 11 12

all the 12 numbers will be in the same array but the output must be like 
this.


and if the input is 2, the array must output 12 random numbers




 all i know and read in the book is something like this to print nomally


  System.out.printf(Arrays.toString(array));

  if (i == 1){

  System.out.printf("%5s", Arrays.toString(array))   ;

 }


     int i = input.nextInt();

    int[] array = {1,2,3,4,5,6,7,8,9,10,11,12};

  System.out.printf(Arrays.toString(array));

  if (i == 1){

  System.out.printf("%5s", Arrays.toString(array))   ;

 }


  I wanted the print to be >1 2 3 4 5 6 7 8 /n 9 10 11 12 

  but the output is within sets {}


红颜莎娜
浏览 92回答 2
2回答

哔哔one

您可以不用这种方式进行核心打印:ifpublic class TTest1 {&nbsp; &nbsp; public static void main(String... args) {&nbsp; &nbsp; &nbsp; &nbsp; int[] array = {1,2,3,4,5,6,7,8,9,10,11,12};&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0 ; i < array.length ; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%5d%s", array[i], (i % 8 == 7)? "\n\n" : "");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}结果:1&nbsp; &nbsp; 2&nbsp; &nbsp; 3&nbsp; &nbsp; 4&nbsp; &nbsp; 5&nbsp; &nbsp; 6&nbsp; &nbsp; 7&nbsp; &nbsp; 89&nbsp; &nbsp;10&nbsp; &nbsp;11&nbsp; &nbsp;12

忽然笑

您可以使用扫描仪从用户处获取输入:Scanner input = new Scanner(System.in);int i = input.nextInt();if(i == 1) {&nbsp; &nbsp; int[] array = {1,2,3,4,5,6,7,8,9,10,11,12};&nbsp; &nbsp; for(int ind = 0; ind < array.length; ind++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%5d ", array[ind]);&nbsp; &nbsp; &nbsp; &nbsp; if(ind == 7) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(); //to have 8 numbers on the first line&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}}else {&nbsp; &nbsp; &nbsp;//write code for random number generation here&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答