我目前正在对Java类进行介绍,我真的很想改进,但是我在努力完成这项作业。分配要求是
我相信我已经做完了,除了上一个,我已经尝试了很多次使用do和while循环,但是我得到的最接近的是错误的输入循环,而正确的输入将绕过所有其他if / while / else语句。如果有可能,我将非常感谢有人查看我的代码并解释我可以做得更好的方法,以及如何完成或满足最后一个要求。
谢谢!
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input, inputUpper;
char userGuess;
char coinFlip;
int randNum;
int wins = 0;
int losses = 0;
int total = 0;
String choice = "yes";
do {
System.out.print("I will flip a coin guess 'H' for heads or 'T' for
tails --> ");
input = scan.nextLine();
inputUpper = input.toUpperCase();
userGuess = inputUpper.charAt(0);
randNum = (int) (Math.random() * 2);
if(randNum == 0)
{
coinFlip = 'H';
}
else
{
coinFlip = 'T';
}
System.out.println("\nYou picked " + userGuess +
" and the coin flip was " + coinFlip + " so ...");
if(userGuess == coinFlip)
{
System.out.println("You win!");
wins ++;
total ++;
}
else
{
System.out.println("Better luck next time ...");
losses ++;
total ++;
}
System.out.println("Do you want to continue(yes/no)?");
choice=scan.nextLine();
} while(choice.equalsIgnoreCase("yes"));
System.out.println("Thank you for playing.");
System.out.println("You guessed correctly this many times: " +wins);
System.out.println("You guessed incorrectly this many times: " +losses);
System.out.println("During this session you've played this many games: " +total);
}
}
我希望程序需要T / t或H / h才能继续,并且如果用户输入了错误的字母或数字,它将要求他们输入t或h。
答案 0 :(得分:10)
这是验证输入的简单方法:
do {
System.out.print("I will flip a coin guess 'H' for heads or 'T' for tails --> ");
input = scan.nextLine();
inputUpper = input.toUpperCase();
} while (!inputUpper.equals("T") && !inputUpper.equals("F"));
对于“是” /“否”,您可以在最后做同样的事情。
我认为您在此方面做得很好。