我的程序是一个游戏,用于确定某种动物(狗/鸡/鱼)有多少条腿。
每次运行程序时,我都会收到一条错误消息:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at AnimalGame.main(AnimalGame.java:67)".
我找不到问题。另外,我希望程序在“你赢了!”之后结束。或“你输了!”,但每次它说其中一个输出时,它都会说
“我不认识那只动物。你想再试一次吗?(y/n)”
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char n = 0;
char y = 0;
char gameAnswer = 'n';
do
{
System.out.println("Choose an animal: ");
String text = input.nextLine();
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if(dg == 4)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if(chkn == 2)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if(fsh == 0)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
default:
break;
}
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
gameAnswer = input.nextLine().charAt (0);
}while(gameAnswer == 'y');
}