随机填充具有某些限制的二维阵列

时间:2015-11-07 21:55:38

标签: java arrays

所以,我必须用预先确定的单词随机填充一个字符串数组,但是每个单词的数量都可以是数组上限的数量。 这是我编码但它返回一个空数组,我不知道为什么:

package test;

import java.util.Random;

public class Main {

    public static void main (String []args){
        String [][] array = new String [4][4];
        String [] words = new String [6];
        int limits[] = new int [4];
        int counter[] = {0, 0, 0, 0};
        words[0] = "Roberto";
        words[1] = "Matias";
        words[2] = "Carlitos";
        words[3] = "Leonel"; 
        limits[0] = 2;
        limits[1] = 3;
        limits[2] = 5;
        limits[3] = 1; 
        //when filled its true means that the correspondent word has reached its limits.
        boolean filled []= new boolean [4];
        filled [0] = false;
        filled [1] = false;
        filled [2] = false;
        filled [3] = false;

        Random rnd = new Random();
        //not f
        boolean notfilled = true;
        while(notfilled){
            int x = 0, y =0;
            for(int i = 0;i<counter.length; i++ ){
                if(counter[i]==limits[i]){
                    filled[i] = true;
                }


            }
            if (filled[0] == true && filled[1] == true && filled[2] == true && filled[3] == true){
                notfilled = false;
            }
        int rndm = rnd.nextInt(4);
        switch(rndm){
        case 1:{
            if(filled[0] != true){
                array[x][y] = words[rndm];
            }
        }
        case 2:{
            if(filled[1] != true){
                array[x][y] = words[rndm];
            }
        }       
        case 3:{
            if(filled[2] != true){
                array[x][y] = words[rndm];
            }
        }
        case 4:{
            if(filled[3] != true){
                array[x][y] = words[rndm];
            }
        }
        if(x == array.length){
            y++;
            x = 0;
        }else{x++;}
    }
  }


 }
}

质疑mi码的错误以及解决方法

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。 正如Boddington所说,你的限制需要加起来16。 x和y也需要在while循环之外进行初始化,这样它们就不会被重置。

    int x = 0, y =0;
    boolean notfilled = true;
    while(notfilled){

正如Mnemomic所说,案件4永远不会被执行。要解决此问题,请将您的案例设置为0,并在每个案例的末尾添加一个中断。 您的最后一个问题是,如果随机选择的单词用完,代码将跳过矩阵中的空格。要解决此问题,只有在未填充随机字时才需要移动x和y

毕竟你的案例陈述应该是这样的

case 0:{
            if(filled[0] != true){
                array[x][y] = words[0];
                counter[0]++;
                x++;
                if(x == array.length){
                    y++;
                    x = 0;
                }
            }
            break;
        }