循环运行的次数不正确

时间:2015-05-25 11:52:13

标签: java random while-loop boolean

我遇到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;

1 个答案:

答案 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;
     }    
 }