【发布时间】:2012-03-15 19:10:05
【问题描述】:
我希望有人能回答这个问题,所以我会尽力解释清楚。
我的目标是在一行 5 个方格上生成 MAXIMUM 个 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 代码,只是为了让事情变得更简单。
【问题讨论】:
-
我想我可能知道出了什么问题,但我不知道如何实现它。我认为发生的事情是 2 个字母具有相同的位置,不允许另一个字母获得正方形。
-
请您发布一个可编译的代码,我可以为您测试!!
-
@GagandeepBali 你好!实际上,这是一个可编译的代码。它不适合你吗?
-
@GagandeepBali 我不确定它是否有效,但我打算将那个 while 循环放在那里,以希望删除我的字母的重复项。整个 while 循环“过滤”重复项,不允许它进入 numArray。
-
作为旁注,我想建议使用 java.util.Random 类来生成随机整数,而不是 Math.random() 方法相乘然后四舍五入。此外,为了从预定义的一组元素中选择随机元素而不出现重复,请将它们添加到列表中,使用Collections.shuffle(list),然后从列表中取出前 n 个元素。
标签: java loops multidimensional-array letter