在一行上打印随机数组:Java

时间:2015-10-20 22:46:37

标签: java arrays for-loop random tostring

构建一个可以在数组中生成随机整数值的数组。它打印随机数,但它会像这样打印出来 [10] [2] [5] [7] [6] [2] [4] [7] [2] [10] [0] --->(向下)------- - >并希望它像这样打印[10,7,5,9,4,3,4,7,2,3](一行)。

    }
    else if(journey == 2) {
        if (london != 0) {
            london--;
            System.out.println("Journey to london booked");
            System.out.println("Number of tickets left for london : " + london);
        }

    } 
    else if(journey == 3) {
        if (krakow != 0) {
            krakow--;
            System.out.println("Journey to krakow booked");
            System.out.println("Number of tickets left for krakow : " + krakow);
        }
    }

}

}

1 个答案:

答案 0 :(得分:2)

只需更改

System.out.println(Arrays.toString(array1)); 
//new output
System.out.print(Arrays.toString(array1));

另一种完成此任务的方法是使用for循环以类似的方式迭代数组

for( int i = 0; i < array1.length; i++ ){
    System.out.print(array1[i]+" ");
}

为随机数

Random ran = new Random();
for( int i = 0; i < array1.length; i++ ){
    int number = ran.nextInt((max - min) + 1) + min;
    //insert the maximum and min values for your generator
    array1[i] = number;