Java charAt() 字符串索引超出范围

Java charAt() String index out of range

我正在尝试使用此代码找出 "what 5-digit number when multiplied by 4 gives you its reverse?",但出现错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 5 at java.lang.String.charAt(String.java:658) at     
Digits.main(Digits.java:15)

我想弄清楚(请人解释)为什么会这样。我想在我的代码中保留我的 charAt,如果可能的话不使用 StringBuilder (StringBuilder.reverse())

public class Digits{
  public static void main(String[] args) {
    int n = 0;
    int b = 0;
    String number = "";
    String backwards = "";

    for (int x = 9999; x <= 99999 ; x++ ) {
      n = x;
      b = x * 4;
      number = Integer.toString(n);
      backwards = Integer.toString(b);

      if ( number.charAt(0) == backwards.charAt(4) && number.charAt(1) == backwards.charAt(3)
      && number.charAt(2) == backwards.charAt(2) && number.charAt(3) == backwards.charAt(1)
      && number.charAt(4) == backwards.charAt(0)) {
        System.out.println(n);
        break;
      }
    }

谢谢

此代码不可能出现此异常。您没有任何 chatAt(5)。请再次查看。

代码运行无异常,测试代码如下:

public class Digits {

    public static void main(String[] args) {
        int n;
        n = 0;
        int b;
        b = 0;
        String number;
        number = "";


    String backwards;
        backwards = "";

        for (int x = 9999; x <= 99999; x++) {
            n = x;
            b = x * 4;
            number = Integer.toString(n);
            backwards = Integer.toString(b);

            if (number.charAt(0) == backwards.charAt(4) && number.charAt(1) == backwards.charAt(3)
                    && number.charAt(2) == backwards.charAt(2) && number.charAt(3) == backwards.charAt(1)
                    && number.charAt(4) == backwards.charAt(0)) {
                System.out.println(n);
                break;
            }
        }
    }
}

这段代码的输出是 21978