Reputation: 11
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!
Upvotes: 1
Views: 11312
Reputation: 30733
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.
Upvotes: 5
Reputation: 1503649
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.
Upvotes: 8