我试图弄清楚“乘以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;
      }
    }


谢谢

最佳答案

该代码运行无一例外,下面给出了经过测试的代码:

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

关于java - Java charAt()字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31376161/

10-13 09:53