2016-04-23 34 views
0

我正在嘗試學習java,並將代碼從岩石紙剪刀遊戲從python轉換爲java。我現在正面臨的一個問題是讓Scanner在每個循環中都得到新的答案。這是我現在所擁有的。java如何在循環中使用1臺掃描儀

import java.util.Scanner; 

public class PlayerInput { 

public static String playerChoice(){ 
    String Pchoice; 
    Pchoice = "n"; 
    Scanner pChoice = new Scanner(System.in); 
    while(pChoice.hasNextLine()){ 
    Pchoice = pChoice.nextLine(); 
    Pchoice = capitalizeFirstLetter(Pchoice); 
    if(Pchoice.equals("R")||Pchoice.equals("Rock")||Pchoice.equals("P")||Pchoice.equals("Paper")||Pchoice.equals("S")||Pchoice.equals("Scissors")){ 
    break; }} 
    pChoice.close(); 
     if(Pchoice.equals("R")||Pchoice.equals("Rock")){ 
      Pchoice = "Rock"; 
     }else if (Pchoice.equals("P")||Pchoice.equals("Paper")){ 
      Pchoice = "Paper"; 
     }else if (Pchoice.equals("S")||Pchoice.equals("Scissors")){ 
      Pchoice = "Scissors"; 
     }else { 
      System.out.println("Please try again and enter Rock (R), Paper(P), or Scissors(S)"); 
      playerChoice(); 
     } 
    return Pchoice; 
} 


public class Start { 

public static void main(String[] args) { 

    PlayerInput magic = new PlayerInput(); 

    String name = magic.nameGetter(); 
    System.out.println("Hello " + name); 

    for(int x = 0; x <=5; x++){ 
    String Pchoice = PlayerInput.playerChoice(); 
    System.out.println("You chose: " + Pchoice); 
    } 
    PlayerInput.playAgain(); 
} 
} 

我確實有通過這兩個調用的其他函數/方法我只是沒有在這裏包括它們。

回答

1

不要關閉您的playerChoice方法中的掃描儀,如果您打開它並在主要方法中關閉它會更好