开发者

StringIndexOutOfBoundsException: String index out of range: 0

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();
开发者_StackOverflow社区 }
 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...".

Please help, this is driving me batty!


That will happen if another is the empty string.

We don't know what the Keyboard class is, but presumably its nextLine method can return an empty string... so you should check for that too.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜