StringIndexOutOfBoundsException:字符串索引超出范围:0

1 java indexing

我得到一个奇怪的异常代码.

我尝试使用的代码如下:

 do
 {
  //blah blah actions.

     System.out.print("\nEnter another rental (y/n): ");
     another = Keyboard.nextLine();
 }
 while (Character.toUpperCase(another.charAt(0)) == 'Y');
Run Code Online (Sandbox Code Playgroud)

错误代码是:

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)
Run Code Online (Sandbox Code Playgroud)

第57行是"while ......"开始的行.

请帮帮忙,这让我慌张!

Jon*_*eet 8

如果another是空字符串,那将会发生.

我们不知道这个Keyboard类是什么,但可能它的nextLine方法可以返回一个空字符串...所以你也应该检查它.


Ita*_*man 5

固定:

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');
Run Code Online (Sandbox Code Playgroud)

甚至更好:

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');
Run Code Online (Sandbox Code Playgroud)

如果您不小心按Enter,则第二个版本不会打印"输入另一个租借".