我想弄清楚爲什麼我的程序反覆打印相同的語句。當我輸入好的值時,我能夠使此方法正常工作,但我設置了一個else語句來捕獲無效的選擇。當我的else語句運行時,它會無限打印,而while循環永遠不會開始。我無法弄清楚。我要粘貼整個方法,但大膽的問題領域。我希望這很清楚。雖然循環陷入無限循環
public static int[][] placeCheese(int [][] gameBoard, String Player1Name)
{
Scanner console = new Scanner(System.in);
int turnTaker = 0;
int validRow = 0;
int validCol = 0;
int RowIndex = -1;
int ColIndex = -1;
while(turnTaker == 0)
{
while(validRow == 0)
{
System.out.println(Player1Name + ", please place your cheese by choosing a row, or choose -1 to exit.");
RowIndex = console.nextInt() -1;
if(RowIndex < gameBoard.length && RowIndex >=0)
{
validRow++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
while(validCol == 0){
System.out.println(Player1Name + ", please place your cheese by choosing a column, or choose -1 to exit.");
ColIndex = console.nextInt() -1;
if(ColIndex < gameBoard.length && ColIndex >=0)
{
validCol++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
if(gameBoard[RowIndex][ColIndex] == 0)
{
gameBoard[RowIndex][ColIndex] = 1;
turnTaker++;
numPieces1--;
}
else
{
System.out.println("this space is already occupied, please choose again.");
}
return gameBoard;
}
請嘗試將代碼格式化爲更具可讀性的內容.. – nfechner
Gah我正處於編輯過程中,它不允許我保存它。 –
如果在調試進入無限循環時進行調試,您會看到什麼?這個工具可能會幫助你解決問題,因爲這是它的目的。 –