首页 > 解决方案 > 字符串索引超出范围异常错误

问题描述

我正在为我的作业编写代码,但我收到此异常错误:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:9 在 java.lang.String.charAt(未知来源)

这是代码:

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);
            }
        }

    }

谢谢!

标签: javaerror-handling

解决方案


推荐阅读