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

时间:2017-03-29 00:48:08

标签: java

我试图创建使用单个while循环的程序段,该循环执行其循环体五次,每次显示来自这组值的随机数字。 {1,2,3,4,5,6} while循环只执行一次enter code here

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);

我也尝试用数组做到这一点。

 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);

任何提示都会有所帮助。

2 个答案:

答案 0 :(得分:1)

while循环没有大括号,因此正文只是下一个语句。以count为增量。添加大括号。

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

或者,在Java 8+中,IntStream喜欢

IntStream.generate(() -> (int) (Math.random() * 6))
        .limit(5).forEachOrdered(System.out::println);

答案 1 :(得分:0)

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

例如:

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'循环:

for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);                   
    System.out.println(num);
}
相关问题