2016-11-20 76 views
0

我目前正在努力實現while循環在我的遊戲中,因爲它總是給我一個無限循環。我們的想法是繼續比賽,除了只有當用戶鍵入「-1」無限循環在搖滾紙剪刀循環遊戲

// declare variables 
    int player, computer; 
    int counter = 0; 
    // player input 
    System.out.println("Rock, Paper, Scissors!"); 
    System.out.print("Enter 0 for paper, 1 for Scissors, or 2 for Rock (-1 to quit) : "); 
    player = sc.nextInt(); 
    while (player != -1) { 

     // switch statement for player 
     switch (player) { 
     case 0: 
      System.out.println("Player picks Paper"); 
      break; 
     case 1: 
      System.out.println("Player picks Scissors"); 
      break; 
     case 2: 
      System.out.println("Player picks Rock"); 
      break; 
     case -1: 
      System.exit(-1); 
      break; 
     default: 
      System.out.println("Invalid input"); 
     } 

     // generate a random number for computer 
     Random randomGen = new Random(); 
     computer = randomGen.nextInt(3); 

     // switch statement for computer 
     switch (computer) { 
     case 0: 
      System.out.println("Computer picks Paper"); 
      break; 
     case 1: 
      System.out.println("Computer picks Scissors"); 
      break; 
     case 2: 
      System.out.println("Computer picks Rock"); 
      break; 
     default: 
     } 

     // output for each condition 
     if (player == 2 && computer == 1) 
      System.out.println("Player Wins!"); 
     else if (player == 1 && computer == 0) 
      System.out.println("Player Wins!"); 
     else if (player == 0 && computer == 2) 
      System.out.println("Player Wins!"); 
     else if (computer == 1 && player == 0) 
      System.out.println("Computer Wins!"); 
     else if (player == 0 && computer == 2) 
      System.out.println("Computer Wins!"); 
     else if (player == 1 && computer == 2) 
      System.out.println("Computer Wins!"); 
     else 
      System.out.println("Draw"); 
     sc.close(); 
    } 
+1

你有這條線重複:'否則,如果(球員== 0 &&電腦= = 2)'。如果第二次(否則)(電腦== 0 && player == 2)? –

回答

1

你永遠不更新player值。將player = sc.nextInt()添加到循環體的末尾。 或者,這樣做

int player; 
while ((player = sc.nextInt()) != -1) { 

,我相信你也應該刪除調用sc.close();

+0

使用後關閉「掃描儀」是個好習慣 - 爲什麼不呢? –

+1

@ OleV.V。 OP正在關閉**循環體中的'Scanner' **。另外,它可能會封裝'System.in',所以關閉'Scanner'也會關閉'System.in' * global *。最後,我更傾向於['try-with-resources'](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)通過顯式關閉(如果不是這樣的話)。 –

+0

同意它應該移到循環之外。爲了方便起見,我也會使用try-with-resources(在這種情況下,我猜'sc'是在方法外部聲明的;如果是這樣,則不可能嘗試使用資源,並且調用close()應該去爲了清楚起見,也存在該方法的缺點)。 –