Java 错误消息 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4039368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java error message java.lang.StringIndexOutOfBoundsException: String index out of range: 0
提问by MrRogers04
here is my program
这是我的程序
import java.util.Scanner;
import java.util.Random;
public class Project3
{
public static void main(String[] args)
{
int low;
int high;
int answer;
int guess;
int numGuess = 0;
int x;
int y;
char repeat; // this will hold y or n
String input; //holds input to perform entire loop
System.out.println( "Hello and welcome to Guess That Number!");
Scanner keyboard = new Scanner(System.in);
System.out.println("For starters you get to pick the range the number falls in!" +
" HOW EXCITING!");
System.out.println( "Now what would you like the lowest possible number to be?");
low = keyboard.nextInt();
System.out.println( "and the highest?");
high = keyboard.nextInt();
do
{ Random randomNumber = new Random();
answer = randomNumber.nextInt();
while (answer < low || answer > high)
{
answer = randomNumber.nextInt();
}
guess = -1;
while(guess != answer)
{
System.out.println("What is your guess?");
System.out.println("Don't forget has to be in between "+ low + " and " + high);
guess = keyboard.nextInt();
numGuess = (numGuess + 1);
if (guess < answer)
{
System.out.println("TOO LOW!");
}
else if (guess > answer)
{
System.out.println("TOO HIGH!");
}
}
System.out.println("YOU GOT IT WOOOO!");
System.out.println("The number was " + answer);
System.out.println("Nice it only took " + numGuess + "!");
for ( x = 1; x <= numGuess; x++)
{
for ( y = 1; y <= answer; y++)
{
System.out.print("*");
}
System.out.println();
}
System.out.println("\nWould you like to play again? \n" + // this is to loop the entire game
"Enter Y for yes or N for no. \n");
input = keyboard.nextLine();
repeat = input.charAt(0);
} while (repeat == 'Y' || repeat == 'y');
if (repeat == 'n' || repeat == 'N')
{
System.out.println("\nThanks for playing! \n");
}
}
}
when i try and run it it gives me this error message
当我尝试运行它时,它给了我这个错误信息
java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:687)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:687)
how do i fix it so the program loops correctly?!?
我如何修复它以便程序正确循环?!?
回答by zerodin
before you do this: repeat = input.charAt(0);
在你这样做之前: repeat = input.charAt(0);
check if the string
has at-least
one character.
检查是否string
有at-least
一个字符。
回答by Owen
IndexOutOfBoundsException means the index you're trying to access of the array does not exist. The exception shows you it's encountering the error at line 687 and it's the String.charAt() method. I'd recommend by taking a closer look at your code around that line. If you're using an IDE, you should try executing in debug with a breakpoint near that line and stepping through the code line by line to watch the variables.
IndexOutOfBoundsException 表示您尝试访问的数组索引不存在。异常显示它在第 687 行遇到错误,它是 String.charAt() 方法。我建议仔细查看该行周围的代码。如果您使用的是 IDE,您应该尝试在调试中使用该行附近的断点执行,并逐行逐行执行代码以观察变量。
回答by Yanick Rochon
First, just a side note, as mootinatorstated, your while
condition will be false if any input is not 'Y'
or 'y'
, thus exit and the final "\nThanks for playing! \n"
will never be displayed. You should revise this construct. Perhaps something like :
首先,只是一个旁注,正如mootinator所说,while
如果任何输入不是'Y'
or 'y'
,你的条件将是假的,因此退出并且最终"\nThanks for playing! \n"
将永远不会显示。你应该修改这个结构。也许是这样的:
boolean playing = true;
while (playing) {
// play game here
// ask to play again?
if (answer == 'N') {
playing = false;
}
}
System.out.println("\nThank you for playing!\n");
Now, to address your original problem, you are not checking for empty input. The error is very likely to happen only when you hit enter without entering anything. Another question is then, what to do with empty values? Is it considered to be 'N'
or 'Y'
? If you consider empty value to be a valid default choice, you should indicate it in your displayed question. Something like:
现在,为了解决您的原始问题,您没有检查空输入。仅当您在不输入任何内容的情况下按 Enter 时,该错误很可能会发生。另一个问题是,如何处理空值?它被认为是'N'
或'Y'
?如果您认为空值是有效的默认选择,则应在显示的问题中指出它。就像是:
System.out.print("\nWould you like to play again?\n" +
"Enter Yes or No (default Yes) : ");
do {
input = keyboard.nextLine().toUpperCase(); // 'Y' == 'y';
if (input.length() == 0) { // if the input is empty, we default the value
repeat = 'Y'; // default value, change this to 'N' if default is No
} else {
repeat = input.charAt(0);
if (repeat != 'N' && repeat != 'Y') {
System.out.print("Ooops! Please enter Yes or No :");
repeat = 'System.out.print("\nWould you like to play again?\n" +
"Enter Yes or No : ");
do {
input = keyboard.nextLine().toUpperCase(); // 'Y' == 'y';
if (input.length() == 0) { // if the input is empty...
repeat = 'repeat = input.charAt(0);
'; // null character for empty value
} else {
repeat = input.charAt(0);
}
if (repeat != 'N' && repeat != 'Y') {
System.out.print("Ooops! Please enter Yes or No :");
repeat = 'try
{
repeat = input.charAt(0);
}
catch (java.lang.StringIndexOutOfBoundsException exception)
{
//Solve the problem
}
'; // make sure the character is null so we don't exit the loop yet
}
} while (repeat == 'do {
.....
} while ("y".equalsIgnoreCase(input));
if (!"y".equalsIgnoreCase(input)) {
System.out.println("\nThanks for playing! \n");
}
');
// At this point, repeat is either 'Y' or 'N' only, so no need to check for lowercase
';
}
}
} while (repeat == '##代码##');
// At this point, repeat is either 'Y' or 'N' only, so no need to check for lowercase
If you don't want a default value, simply change the construct to
如果您不想要默认值,只需将构造更改为
##代码##回答by Lajos Arpad
Instead of this:
取而代之的是:
##代码##Do this:
做这个:
##代码##This way you can catch your exception and handle it. EDIT: It's better to learn a little Exception handling in Java in your first lesson, because it's not complicated and will be useful at later, more difficult tasks.
这样你就可以捕捉你的异常并处理它。编辑:最好在第一课中学习一些 Java 中的异常处理,因为它并不复杂,并且在以后的更困难的任务中会有用。
回答by Adeel Ansari
It seems that the user is pressing return/enter
without inputing Y
or N
.
似乎用户在return/enter
没有输入Y
或 的情况下按下N
。
Here is the suggestion. No doubt that the code can be made better in many ways, but this is just a suggestion for this very issue. Get rid of the repeat
variable completely, and replace respective lines with these.
这是建议。毫无疑问,代码可以在很多方面做得更好,但这只是针对这个问题的一个建议。repeat
完全摆脱变量,并用这些替换相应的行。