so, i have to randomly fill an string array with predeterminated words but each word has a limit ammount of times it can be on the array
This its what i coded but it returns a null array and i dont khow why:
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++;}
}
}
}
}
question its what its wrong with mi code and how to fix it
There are a couple problems with your code. As Boddington mentioned your limits need to add up to 16. Also x and y need to be initialized outside the while loop so they won't be reset.
int x = 0, y =0;
boolean notfilled = true;
while(notfilled){
As Mnemomic said case 4 will never be executed. To fix this start your cases at 0 and add a break to the end of each case. Your last problem is that the code will skip a space in the matrix if the randomly selected word is used up. To fix this you need to move x and y only if the random word is not filled
After all that your case statements should look like this
case 0:{
if(filled[0] != true){
array[x][y] = words[0];
counter[0]++;
x++;
if(x == array.length){
y++;
x = 0;
}
}
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.