gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:00:56 25 4
gpt4 key购买 nike

我正在尝试学习java,并将石头剪刀布游戏的代码从python 转换为java。我现在遇到的一个问题是让扫描仪在循环中每一轮都得到一个新的答案。这就是我现在所拥有的。

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();
}
}

我确实通过这两个函数/方法调用了其他函数/方法,只是这里没有包含它们。

最佳答案

不要在playerChoice方法中关闭Scanner,最好在main方法中打开它并关闭它

关于java 如何在循环中使用1个扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com