2017-06-19 85 views
0

我對此代碼有問題。 我看到的問題是,當用戶運行代碼並猜測正確或使用最大嘗試次數時,while循環不會啓動並允許遊戲重新啓動。 我的想法是將計數器(嘗試)重置爲零並重新開始,但我只是以總分來獲得退出消息。如何在數字猜測遊戲循環時重新啓動

int guess = 0; 
    int attempt = 0; 
    int number = new Random().nextInt(1000) + 1; 
    int scorePlayer = 0; int scoreComputer = 0; 
    boolean repeat; 

    System.out.println("Hello and welcome to the number guessing game."); 
    System.out.println("Please guess a number between 1 and 1000"); 


    while(repeat == true){ 
     do{ 
      Scanner scan = new Scanner(System.in); 
      guess = Integer.parseInt(scan.nextLine()); 
      System.out.println("The number you guessed is "+guess); 
      attempt++; 

      if(guess == number){ 
       System.out.println("Congratulations! You got it!!"); 
       scorePlayer++; 
       System.out.println("Would you like to play again? [YES/NO]"); 
       Scanner a = new Scanner(System.in); 
       String answer = a.nextLine().toUpperCase(); 
       if (answer != "YES"){ 
        //repeat = false; 
        System.out.println("Thank you for playing"); 
        System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server"); 
        if (scorePlayer<scoreComputer){ 
         System.out.println("Computer wins!"); 
        }else{ 
         System.out.println("You win!"); 
        }break; 
       }else{ 
        attempt = 0; 
       } 
      }else if(guess < number){ 
       System.out.println("That is incorrect, try a larger number"); 

      }else if(guess > number){ 
       System.out.println("That is incorrect, try a smaller number"); 

      }if(attempt == 10 && guess != number){ 
       System.out.println("That is the max number of guesses allowed"); 
       System.out.println("The number you were looking for is "+number); 
       scoreComputer++; 
       System.out.println("Would you like to play again? [YES/NO]"); 
       Scanner b = new Scanner(System.in); 
       String answer = b.nextLine().toUpperCase(); 
       if (answer != "YES"){ 
        //repeat = false; 
        System.out.println("Thank you for playing"); 
        System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server"); 
        if (scorePlayer<scoreComputer){ 
         System.out.println("Computer wins!"); 
        }else{ 
         System.out.println("You win!"); 
        }break; 
       }else{ 
        attempt = 0; 
       } 
      } 

     }while(guess != number || attempt == 0); 
     repeat = false; 
    } 
+0

假設你修正了編譯器錯誤'while(repeat = true)':你在第一個內部'do-while'循環完成之後直接''repeat'設置爲'false'。那麼外環的想法是什麼呢?它只運行一次。 – AKSW

回答

2

單個「=」是一個賦值操作符,只需將其更改爲雙「==」即可。

while(repeat == true) 
+0

這不能解決問題,這個問題不是由於那個錯字導致的,所以我認爲這個問題可能在別處。該代碼不允許遊戲在正確的數字被猜測或用戶用完嘗試後重新啓動 – user3018640

1

除了UGUR說什麼,你可以簡單地做

while(repeat) 

,因爲重複是一個布爾變量(返回true或false)

0

檢查的最後一行在外環你正在設置repeat=false。所以當你從內循環break,外while檢查重複,這是每一次,除了第一次是錯誤的。