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

时间:2015-07-13 05:49:15

标签: java string indexing charat

我试图找出“当乘以4时,5位数字给你的反转?”使用此代码,但我收到错误:

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

由于

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

此代码无法执行此例外。你没有任何聊天(5)。再次检查。