So I've tried looking through other threads with similar problems, but I couldn't really relate them to my current problem as most of them were suggesting solutions that I haven't been currently taught in my Computer Science 1 college class.
Anyways, if you'll look at my code, I'm trying to get user input to either continue the code and do more calculations, or to stop the program. They'll either type y for yes to continue or any other character to terminate the program. Everything seems to work up until after I enter my next value for cardNumber. It uses my service class, does the math and everything, and then asks if I want to continue again but then I'm told.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:44)
at java.base/java.lang.String.charAt(String.java:692)
at CreditCardDemo.main(CreditCardDemo.java:48)
Now I looked through other threads as I said, and have seen similar errors before, but I still don't understand what this error is telling me or how to fix it. I'm looking at line 48 like the error suggests and I still don't understand why I'm getting this error, especially since I used the
repeat = input.charAt(0);
kb.nextLine();
previously in my code and it worked fine...
I'm really sorry if there's some thread I missed that's super explanatory and would have helped me but I wasn't able to find it if it existed. Can anyone help me out here?
public class CreditCardDemo
{
public static void main(String [] args)
{
int cardNumber;
String input;
char repeat;
Scanner kb = new Scanner(System.in);
CreditCard card1 = new CreditCard(67034014);
CreditCard card2 = new CreditCard();
System.out.print("Enter 8 digit credit card number: " + card1.getCardNumber());
card1.outputTest();
System.out.println();
System.out.println("Continue(y/n)?");
input = kb.nextLine();
repeat = input.charAt(0);
if (repeat != 'y')
{
System.exit(0);
}
do
{
System.out.print("Enter 8 digit credit card number: ");
card2.setCardNumber(kb.nextInt());
card2.outputTest();
System.out.println("Continue(y/n)?");
input = kb.nextLine();
repeat = input.charAt(0);
kb.nextLine();
}
while (repeat == 'y');
}
}