java StringIndexOutOfBoundsException:字符串索引超出范围:0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1927042/
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
StringIndexOutOfBoundsException: String index out of range: 0
提问by Chente
I am getting a weird exception code.
我收到一个奇怪的异常代码。
The code that I am trying to use is as follows:
我尝试使用的代码如下:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
another = Keyboard.nextLine();
}
while (Character.toUpperCase(another.charAt(0)) == 'Y');
The error code is:
错误代码是:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at Store.main(Store.java:57)
Line 57 is the one that starts "while...".
第 57 行是以“while...”开头的那一行。
Please help, this is driving me batty!
请帮忙,这让我很生气!
回答by Jon Skeet
That will happen if anotheris the empty string.
如果another是空字符串,就会发生这种情况。
We don't know what the Keyboardclass is, but presumably its nextLinemethod can return an empty string... so you should check for that too.
我们不知道这个Keyboard类是什么,但大概它的nextLine方法可以返回一个空字符串……所以你也应该检查一下。
回答by Itay Maman
Fix:
使固定:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
another = Keyboard.nextLine();
}
while (another.length() == 0 || Character.toUpperCase(another.charAt(0)) == 'Y');
Or even better:
或者甚至更好:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
while(true) {
another = Keyboard.nextLine();
if(another.length() != 0)
break;
}
}
while (Character.toUpperCase(another.charAt(0)) == 'Y');
This second version will not print "Enter another rental" if you accidentally press Enter.
如果您不小心按 Enter,此第二个版本将不会打印“输入另一个租借”。

