为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

红颜莎娜 2022-09-28 14:48:47
所以基本上,如果输入是1,我需要在我的数组中打印12个给定的数字,如果输入是2,我需要打印随机数。格式应如下所示,一行8,块间距为5,底部为4。1 2 3 4 5 6 7 89 10 11 12all 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 {}
查看完整描述

2 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

您可以不用这种方式进行核心打印:if


public class TTest1 {


    public static void main(String... args) {

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

        for (int i = 0 ; i < array.length ; i++)

            System.out.printf("%5d%s", array[i], (i % 8 == 7)? "\n\n" : "");

        System.out.println();

    }

}

结果:


1    2    3    4    5    6    7    8


9   10   11   12


查看完整回答
反对 回复 2022-09-28
?
忽然笑

TA贡献1806条经验 获得超5个赞

您可以使用扫描仪从用户处获取输入:


Scanner input = new Scanner(System.in);

int i = input.nextInt();


if(i == 1) {

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

    for(int ind = 0; ind < array.length; ind++) {

        System.out.printf("%5d ", array[ind]);

        if(ind == 7) {

            System.out.println(); //to have 8 numbers on the first line

        }

     }

}

else {

     //write code for random number generation here

    }


查看完整回答
反对 回复 2022-09-28
  • 2 回答
  • 0 关注
  • 91 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号