如何循环回程序的开头?

时间:2017-11-17 00:07:32

标签: java

我需要循环回到程序的开头。我的程序是tic tac toe,在游戏结束后,我想让程序循环回到开始,如果用户也愿意。我有人回答了我的问题他们告诉我输入“布尔答案=真;”和“while(回答)”。现在我收到一个看起来像这样的错误。 - 找到1个错误: 文件:C:\ Users \ aldor \ Desktop \ Java Coding \ Unit 3 \ Unit3Sumative.java [line:35] 错误:重复的局部变量答案。 - 它在布尔值“answer”= TextIO.getlnBoolean处突出显示。 TextIO.getln是由其他人创建的用户输入。感谢之前帮助过我的人,我是Stack Overflow的新手。谢谢你的帮助。

public class Unit3Sumative {

  static String[][] board;

  public static void main(String[] args) {
    boolean answer = true;
    while(answer)
    {
    board = new String [3][3];
    makeBoard();
    boardTitle();
    do
    {
      printBoard();
      System.out.println("Player X, make your move");
      replace(userMove(),"X"); 
      if(winCheck("X")) break;
      catsGameCheck();
      printBoard();
      System.out.println("Player 0, make your move");
      replace(userMove(),"O");
      if(winCheck("O")) break;
      catsGameCheck();
    } while(true);

    //if player will like to continue to play the game or not
    System.out.println("Would you like to play again?");


    boolean answer = TextIO.getlnBoolean();
    if (answer == true)
    {
      //
    }
    else if (answer == false) 
    {
      System.out.println("Thanks for playing Tic Tac Toe. Hope you enjoyed!");
    }
 }
} 

1 个答案:

答案 0 :(得分:0)

将main方法放在while循环中,检查用户是否想继续播放:

//Assuming player wants to play game
boolean answer = true;

//Keep playing so long as user still wants to
while(answer)
{
  board = new String [3][3];
  makeBoard();
  boardTitle();
  do
  {
    printBoard();
    System.out.println("Player X, make your move");
    replace(userMove(),"X"); 
    if(winCheck("X")) break;
    catsGameCheck();
    printBoard();
    System.out.println("Player 0, make your move");
    replace(userMove(),"O");
    if(winCheck("O")) break;
    catsGameCheck();
  } while(true);

  //See if the player wants to play again
  System.out.println("Would you like to play again?");

  //Updating desire to play again
  answer = TextIO.getlnBoolean();
}