java如何在循环中使用1个扫描程序

时间:2016-04-23 17:34:45

标签: java

我正在尝试学习java并将Rock Paper Scissors游戏的代码从python转换为java。我现在面临的一个问题是让Scanner在循环中每轮获得一个新答案。这就是我现在所拥有的。

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 个答案:

答案 0 :(得分:1)

请勿在playerChoice方法中关闭扫描仪,如果打开它并在主方法中关闭它会更好