我希望有人能回答这个问题,所以我会尽力解释。
我的目标是在5个正方形的直线上最多生成3个唯一的元音(AEIOU)。我已经使用2D数组(board[][]
)制作了25个正方形,但我想先做第一行。图片如下:
现在,我的问题是,每当我尝试在正方形中生成随机字母时,第一个字母都不会显示。例如,我有E
和O
,O
仅显示在我的正方形中,而不显示E
。它在我的控制台中打印,但不在我的GUI中打印。
此外,有时还会显示字母的重复。我不知道如何解决这个问题:
这是我到目前为止完成的代码:
String board[][] = new String[5][5];
String alphabet = "AEIOU";
int numArray[] = new int[5]; //where I can store random indices of alphabet
int finalIndex = 0;
int random = (int) (Math.random()*3) + 1; //random number of vowels to be generated
//this loop covers everything
for(int ctr = 0; ctr < random; ctr++) {
while(ctr != finalIndex) { //checks if there are any duplicates
int rand = (int) (Math.random()*4); //random position for the letter
numArray[ctr] = rand;
while(numArray[ctr] != numArray[finalIndex]) {
finalIndex++;
}
}
//finds the position of the letter in alphabet and converts it to String
char character = alphabet.charAt(numArray[ctr]);
String s = String.valueOf(character);
System.out.println(s);
//loop for putting the letters to the 2D array
for(int i = 0; i < board.length; i++) {
int gen = (int) (Math.random()*4); //random square for letter
for(int j = 0; j <= gen; j++) {
if(i == 0 && j < 5) { //row 1
board[i][gen] = s;
}
}
}
}
我决定不再放置我的GUI代码,只是为了使事情变得更简单。
最佳答案
对不起,我看不懂你的东西,所以我自己尝试了一下...
int rows = 5;
Character [] vowels = {'A','E','I','O','U'};
Character [][] board = new Character [vowels.length][rows];
for(int row = 0;row<rows;row++){
ArrayList<Character> tempVowels = new ArrayList<Character>(Arrays.asList(vowels));
int numVowPerLine = (int)Math.floor(Math.random()*4);
for(int j = 0;j<numVowPerLine;j++){
do{
int pos = (int)Math.floor(Math.random()*5);
if(board[row][pos] == null){
int temp = (int)Math.floor(Math.random()*tempVowels.size());
board[row][pos] = tempVowels.get(temp);
tempVowels.remove(temp);
break;
}
}while(true);
}
}