簡體   English   中英

隨機填充2D數組有一定限制

[英]Randomly filling a 2d array with certain restrictions

因此,我必須用預先確定的單詞隨機填充一個字符串數組,但是每個單詞都有一定數量的限制,可以在數組上使用
這是我編碼的內容,但是它返回一個空數組,我不知道為什么:

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代碼有什么問題以及如何解決

您的代碼有幾個問題。 正如Boddington所提到的,您的限制總共需要加16。此外,x和y需要在while循環之外進行初始化,以便不會被重置。

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

正如Mnemomic所說,案例4將永遠不會執行。 要解決此問題,請在0處開始您的案例,並在每個案例的末尾添加一個中斷。 您的最后一個問題是,如果隨機選擇的單詞用完了,代碼將跳過矩陣中的空格。 要解決此問題,僅當未填充隨機詞時才需要移動x和y

畢竟,您的case語句應如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM