我必须制作一个剪刀石头布程序,让用户输入一个选项,然后根据计算机的选择对其进行测试。每场比赛结束后,它应该询问玩家是否要继续,他们应该输入'Y'或'N'以继续或退出。我能想到的最好的就是一个while循环,除了最后一点,一切都很好。
import java.util.Scanner;
public class rockpaperscissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char cont = 'y';
while (cont == 'y'){
int com = (int)(Math.random() * 3);
System.out.println("Paper (0), Rock (1), or Scizzors (2)?");
int hum = input.nextInt();
if (com==(hum))
System.out.println("It's a tie!");
else if (hum == 0)
{
if (com == 1)
System.out.println ("You chose paper, computer chose rock You Win!");
else if (com == 2)
System.out.println ("You chose paper, Computer chose scissors You Lose!");
}
else if (hum == 1)
{
if (com == 2)
System.out.println ("You chose Rock, computer chose scissors You Win!");
else if (com == 0)
System.out.println ("You chose Rock, Computer chose paper You Lose!");
}
else if (hum == 2)
{
if (com == 0)
System.out.println ("You chose Scissors, computer chose paper You Win!");
else if (com == 1)
System.out.println ("You chose Scissors, Computer chose rock You Lose!");
}
System.out.println("Would you like to continue? (Y/N)");
cont = input.nextLine().charAt(0);
}
}
}
当我运行它时,循环运行良好,游戏已开始,但随后出现“字符串超出索引范围”错误。知道如何解决这个问题吗?