Печать букв в 2D массивах? Первая буква не отображается - PullRequest
1 голос
/ 25 февраля 2012

Я надеюсь, что кто-то может ответить на этот вопрос, поэтому я попытаюсь объяснить это хорошо.

Моя цель - создать МАКСИМАЛЬНЫЙ из 3 уникальных гласных (AEIOU) в строкеиз 5 квадратов.Я сделал 25 квадратов, используя 2D массив (board[][]), но я хочу сделать первую строку первой.Представьте себе это так: enter image description here

Теперь моя проблема в том, что всякий раз, когда я пытаюсь сгенерировать случайные буквы в своих квадратах, первая буква не отображается.Например, у меня E и O, O будет отображаться только в моих квадратах, а не E.Он печатается в моей консоли, но не в моем графическом интерфейсе.

Кроме того, иногда отображаются ДУБЛИКАТЫ букв.Я не знаю, как это исправить: |

Вот коды, которые я сделал до сих пор:

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, просто чтобы сделать вещипроще.

1 Ответ

1 голос
/ 25 февраля 2012

Извините, я не мог прочитать то, что вы имели, поэтому я попробовал это сам ...

    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);
        }
    }
...