为什么我的字符串索引超出范围?
Why is my string index out of range?
正在为抛硬币程序编写嵌套的 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 时,您需要重置输入。目前扫描仪正在寻找下一个 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();
}
解决类型不匹配异常。
正在为抛硬币程序编写嵌套的 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 时,您需要重置输入。目前扫描仪正在寻找下一个 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();
}
解决类型不匹配异常。