Java while循环执行五次,每次显示一个随机数字

Java while循环执行五次,每次显示一个随机数字,java,Java,我试图创建一个程序段,它使用一个while循环来执行它的循环体五次,每次都显示这组值中的一个随机数字。{ 1 , 2 , 3 , 4 , 5 , 6 } while循环只执行一次在此处输入代码 public static void main(String[] args){ int num = 0; int count = 0; while (count < 5) count ++; num = (in

我试图创建一个程序段,它使用一个while循环来执行它的循环体五次,每次都显示这组值中的一个随机数字。{ 1 , 2 , 3 , 4 , 5 , 6 } while循环只执行一次
在此处输入代码

public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);
publicstaticvoidmain(字符串[]args){
int num=0;
整数计数=0;
同时(计数<5)
计数++;
num=(int)(Math.random()*6);
系统输出打印项数(num);
我还尝试用数组来实现这一点

 public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);                   
            System.out.println(num);
publicstaticvoidmain(字符串[]args){
int[]num={1,2,3,4,5,6};
整数计数=0;
同时(计数<5)
计数++;
num[count]=(int)(Math.random()*6);
系统输出打印项数(num);

任何提示都会有帮助。

while循环没有大括号,因此正文只是下一条语句。它增加了
计数
。添加大括号

while (count < 5) {
    count ++;
    num = (int) (Math.random() * 6);
    System.out.println(num);
}

您需要将最后两行放在while循环中

例如:

int[]num={1,2,3,4,5,6};
整数计数=0;
同时(计数<5){
计数++;
num=(int)(Math.random()*6);
系统输出打印项数(num);
}
另一种解决方案是使用“for”循环:

for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);                   
    System.out.println(num);
}
for(int i=0;i<5;i++){
num=(int)(Math.random()*6);
系统输出打印项数(num);
}

你是for循环的核心吗?如果你事先知道要循环多少次,那么使用for循环比使用while循环更容易,但是使用while循环当然也是可能的。
(int)(Math.random()*6)
返回一个介于0和5之间(包括0和5)的随机数。我需要一个while循环。我知道使用for循环更容易。值得注意的是,自动缩进指出了这一点。请务必注意。在Java 8中,您可以使用
new random().int(5,1,7)
.Hah.我发誓我以前试过,但它不起作用。好吧,但现在我也弹出了一个随机0。我怎么才能摆脱它呢?@Ilias
Math.random()*6
给你的数字在(包括)范围
0-5
。如果你想
1-6
,只要加1.
1+(int)(Math.random()*6);
int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
int count = 0;
while (count < 5) {
    count++;
    num = (int)(Math.random()* 6);                   
    System.out.println(num);
}
for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);                   
    System.out.println(num);
}