-
Java Exception help
Hi there, I am trying to write a program for a class and I ran into this bug:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -8
at java.lang.String.substring(String.java:1937)
at java.lang.String.substring(String.java:1904)
at CreditCard.main(CreditCard.java:15)
Java Result: 1
My code here:
import java.util.*;
public class CreditCard {
public static void main(String[] args) {
Scanner console = new Scanner (System.in);
System.out.print("Please enter an 8-digit credit card number: ");
String cardNum = console.nextLine(); //43589795 or 73652180
int sum = Integer.parseInt(cardNum.substring(1 + 3 + 5 + 7));
System.out.print(sum); //a simple check to see if code is working
}
}
Any help would be greatly appreciated!
Thanks,
Daren
-
Re: Java Exception help
So, which is line 15 of CreditCard.java?
According to the stack trace that's the line which caused the ArrayIndexOutOfBoundsException. Such exception occurs whenever you do an operation on a string using character positions which are either negative or past the end of the string.
-
Re: Java Exception help
Line 15 is: int sum = Integer.parseInt(cardNum.substring(1 + 3 + 5 + 7));
the odd thing is none of these are negetive or past the boundaries of the string. That is, unless I screwed up somewhere. The string is exactly 8 characters
-
Re: Java Exception help
I figured it out. The compiler was adding all of the values together in order to find one value, which was in turn 8 over the amount of integers available to choose from. Is there a way to get all 4 digits in one line of code? or do I need 4 separate lines?
-
Re: Java Exception help
No, you'll need to extract the digits of interest one at a time and add their corresponding int values together.
As always the API docs for substring() will help. Notice how it comes in two flavours.