[英]java How to use 1 scanner in a loop
I am trying to learn java and am converting code for a Rock Paper Scissors game from python to java. 我正在尝试学习Java,并且正在将剪刀石头布游戏的代码从python转换为java。 The one issue I have right now is getting Scanner to get a new answer each round in a loop. 我现在遇到的一个问题是让Scanner在循环中每轮获得一个新的答案。 here is what I have right now. 这就是我现在所拥有的。
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();
}
}
I do have the other functions/methods called through these two I just didn't include them here. 我确实有通过这两个调用的其他函数/方法,我只是在这里没有包括它们。
不要在playerChoice方法中关闭扫描仪,最好打开并在主方法中关闭它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.