简体   繁体   中英

Java charAt() String index out of range: 5

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:12)

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

for (int x = 9999; x < 100000 ; x++ ) {
  n = x;
  b = x *4;

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

Any help would be grealy appreciated

Correct. Because the first five characters are at indices 0, 1, 2, 3 and 4 . I would use a StringBuilder (because of StringBuilder.reverse() ). And, I would suggest you restrict variable visibility. Then remember to modify number and backwards when you change n and/or b . Something like

for (int x = 9999; x < 100000; x++) {
    int n = x;
    int b = x * 4;
    String number = Integer.toString(n);
    String backwards = Integer.toString(b);
    StringBuilder sb = new StringBuilder(number);
    sb.reverse();
    if (sb.toString().equals(backwards)) {
        System.out.printf("%s * 4 = %s", number, backwards);
    }
}

And I get

21978 * 4 = 87912

backwards and number are String , which internally uses an array. And an array are indexed from 0 to size-1 . Hence such statements will throw ArrayIndexOutOfBoundsException:

backwards.charAt(5 )
number.charAt(5) 

At the time you create your strings, both of your ints are 0, so both of your strings are "0" for the duration of your program. What you really want is the strings to change every time your number changes. So your code should look more like this:

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

for (int x = 10000; x < 100000 ; x++ ) {
  n = x;
  b = x *4;

  number = Integer.toString(n);
  backwards = Integer.toString(b)

  . . .
}

In addition, arrays in Java are zero-indexed, so for instance for the string "10000", your program will throw the index out of bounds exception on backwards.charAt(5) because the string is indexed from character 0 to character 4.

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