简体   繁体   中英

Java charAt() String index out of range

I am trying to figure out "what 5-digit number when multiplied by 4 gives you its reverse?" using this code but I get error:

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)

I would like to figure out (have someone explain) why this is happening. I would like to keep my charAt in my code and not use StringBuilder (StringBuilder.reverse()) if that is possible.

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

Thanks

The code runs without an exception, the code tested is given below:

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

Ouput of this code is 21978

This exception is not possible for this code. you donot have have any chatAt(5).Check again .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM