Java charAt() String index out of range: 5

点点圈 提交于 2020-02-04 08:07:12

问题


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


回答1:


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



回答2:


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) 



回答3:


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.



来源:https://stackoverflow.com/questions/31375307/java-charat-string-index-out-of-range-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!