gpt4 book ai didi

java - 为什么我的字符串索引超出范围?

转载 作者:行者123 更新时间:2023-11-30 07:04:23 27 4
gpt4 key购买 nike

为硬币翻转程序编写嵌套 while 循环,但我不知道为什么我的代码无法编译。最后的用户输入给了我索引超出范围错误。有人可以告诉我如何解决这个问题吗?

 Scanner lit = new Scanner(System.in);
int numHeads = 0;
int numTails = 0;
int counter = 0;
boolean tryAgain = false;
String replayResponse = "";
char replay = '0';

System.out.println("Enter how many times a coin should be flipped");
int numFlipped = lit.nextInt();

do {

do{


if (Math.random() > 0.5){
System.out.println("H");
numHeads++; counter++;
}

else if (Math.random() < 0.5){
System.out.println("T");
numTails++; counter++;
}


} while(counter < numFlipped);

tryAgain = true;

} while (!tryAgain);

System.out.println("Number of heads is " + numHeads);
System.out.println("Number of tails is " + numTails);
System.out.println("");
System.out.println(" Would you like to play again? : Y/N ");


replayResponse = lit.nextLine();
replay = replayResponse.charAt(0);
if (replay == 'Y' || replay == 'y') {
tryAgain = false;
} else {
tryAgain = true;


}

lit.close();
System.out.println();
System.out.println("You exited out of the game.");
System.out.println("Goodbye!");
}

最佳答案

扫描 int 时,您需要重置输入。目前扫描仪正在寻找下一个整数。因此添加 lit.nextLine(); 像这样:

 lit.nextLine();
replayResponse = lit.nextLine();
replay = replayResponse.charAt(0);
if (replay == 'Y' || replay == 'y') {
tryAgain = false;
} else {
tryAgain = true;

}

您还可以这样做:

if(lit.hasNextInt()) 
{
numFlip = lit.nextInt();
}

解决类型不匹配异常。

关于java - 为什么我的字符串索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391514/

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