0

im writing a code for an assignment i have but im getting this exception error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.lang.String.charAt(Unknown Source)

here's the code:

import java.util.*;

public class ISBN10 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int d10=0;
        System.out.print("Enter the first 9 digits of an ISBN: ");

        String n = in.nextLine();

        if(n.length()!=9)
        {
            System.out.println("You need to enter exactly 9 digits!");
        }
            else

        for(int i = 0; i < n.length(); i++)
        {
            for(int j = 1; j < 10; j++)
            {
                d10 = ((n.charAt(i)*j)+n.charAt(i+1))%11;
            }
        }
            if(d10 == 10)
            {
                System.out.println("The ISBN-10 number is " + n + "X");

            }
            else
            {
                System.out.println("The ISBN-10 number is " + n);
            }
        }

    }

thanks!

Sultnkh
  • 19
  • 2
  • `n.charAt(i+1)` - `i` must be `< n.length() - 1` for this to work. – Jacob G. Feb 22 '20 at 18:36
  • it says it's trying to access index 9, but your string is max 9 character so indexes 0,1,2,3,4,5,6,7,8. I strongly suggest you don't write your code in code. Name variables meaningful names such as instead of String n, String readLine – CausingUnderflowsEverywhere Feb 22 '20 at 18:37

0 Answers0