tags:

views:

214

answers:

2

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...".

Please help, this is driving me batty!

+6  A: 

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.

Jon Skeet
+5  A: 

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.

Itay
Thank you so much! That is an eloquent solution!
Chente
If that works you could flag it as the answer...
extraneon