我遇到while-loop
时遇到问题,因为if语句用于检查按钮是否为空,如果不重复。但是,如果整个if语句在while-loop
中,它在第一次运行代码后会显示大约4个按钮。
case HINT:
Random random = new Random();
int size = SizeOfPuzzle.currentRows;
int randomNumber1 = random.nextInt(size);
int randomNumber2 = random.nextInt(size);
if (puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].getText().isEmpty()) {
puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].setText(puzzle.getSingleLetter(randomNumber1, randomNumber2) + "");
}else {
boolean finished = true;
while (!finished) {
randomNumber1 = random.nextInt(size);
randomNumber2 = random.nextInt(size);
if (puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].getText().isEmpty()) {
puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].setText(puzzle.getSingleLetter(randomNumber1, randomNumber2) + "");
break;
}
}
}
break;
答案 0 :(得分:0)
如果您想要输入片段,则必须将finished
初始化为false
,然后在作业完成后将finished
设置为true
以退出循环
boolean finished = false;
while (!finished) {
// ↑ ↑ ↑ ↑ ↑ →→→→→→ this means loop while finished == false
randomNumber1 = random.nextInt(size);
randomNumber2 = random.nextInt(size);
if (puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].getText().isEmpty()) {
puzzlePanel.arrayOfButtons[randomNumber1][randomNumber2].setText(puzzle.getSingleLetter(randomNumber1, randomNumber2) + "");
finished = true;
}
}