gpt4 book ai didi

java - 我可以在 for 循环中对计数器进行异常(exception)处理吗?

转载 作者:行者123 更新时间:2023-12-01 07:51:08 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,用计算机玩石头、剪刀、布。然而,任务的一部分是让玩家选择与计算机一起玩的回合数。如果出现平局,则该轮不会计入比赛。

我的代码如下所示 - 我更关注程序的 for 部分:

int gamePlays = 0;

for (int = 0; i < gamePlays; i++)
{
// If, else if, and else statements to make the game possible.
// Here is an example of part of the code:
if (cpuChoice.equals ("rock"))
{
if (userChoice.equals ("scissors"))
{
System.out.println("Rock beats scissors, computer wins.");
}
else if (userChoice.equals ("paper"))
{
System.out.println("Paper beats rock, computer wins.");
}
else
{
System.out.println("You both chose rock! It's a tie.");
}
// The rest would else if cpuChoice.equals "paper" and else.
}

当最后一个 else 语句与计数器平局时,如何排除它?我已经为此苦苦挣扎了几个小时,但找不到任何解决方案。

最佳答案

我建议使用 while 而不是 for

int i = 0; 
while (i < gamePlays)
{
// If, else if, and else statements to make the game possible.
// Here is an example of part of the code:
if (cpuChoice.equals ("rock"))
{
if (userChoice.equals ("scissors"))
{
System.out.println("Rock beats scissors, computer wins.");
i++; // increment only when there is result
}
else if (userChoice.equals ("paper"))
{
System.out.println("Paper beats rock, computer wins.");
i++; // increment only when there is result
}
else
{
System.out.println("You both chose rock! It's a tie.");
// don't increment if no result
}
// The rest would else if cpuChoice.equals "paper" and else.
}

}

关于java - 我可以在 for 循环中对计数器进行异常(exception)处理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427405/

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