2016-04-23 48 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方法中的扫描仪,如果您打开它并在主要方法中关闭它会更好