有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

while循环中的Java数组

所以我想知道如何创建一个while循环,其中每个元素最初都设置为0。然后在while循环中有一个随机数选择。假设第一个循环的数字是5,那么数组nums的索引5变为1。假设再次选择5,则nums中的索引5将变为2等。此循环需要继续,直到最后一个索引=1。因此,退出循环的唯一方法是nums数组中的每个索引必须大于或等于1

我提出了下面的循环,但我知道它在内部进行,因为while中的条件是错误的;但是我找不到合适的,我试了一段时间。。。谢谢你的帮助

public class Question1 {

    public static void main(String[] args) {
    int[] nums =  new int [10];
    while ( nums[0]!=1 || nums[1]!=1 || nums[2]!=1 || nums[3]!=1 || nums[4]!=1 || nums[5]!=1 || nums[6]!=1 || nums[7]!=1 || nums[8]!=1 || nums[9]!=1){
        int i = rand.nextInt(10);
        nums[i]++;
}

共 (1) 个答案

  1. # 1 楼答案

    试试这个:

    public static void main(String[] args) {
    
        Random rand = new Random();
        int[] nums =  new int [10];
    
        while (stopTest(nums)){
            int i = rand.nextInt(10);
            nums[i]++;
        }
        //print to test
        System.out.println(Arrays.toString(nums));
    }
    
    private static boolean stopTest(int[] array) {
    
        for(int i: array) {
            if (i<1)    return true;
        }
        return false;
    }