簡體   English   中英

Java charAt()字符串索引超出范圍:5

[英]Java charAt() String index out of range: 5

我試圖弄清楚“乘以4時得到的5位數是多少?” 使用此代碼,但我得到錯誤:線程“主”中的異常java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:Digits.main(Digits.java)處java.lang.String.charAt(String.java:658)為5 :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;
  }
}

任何幫助將不勝感激

正確。 因為前五個字符位於索引0, 1, 2, 34 我將使用StringBuilder (因為StringBuilder.reverse() )。 而且,我建議您限制變量的可見性。 然后記得在更改n和/或b時修改number並向backwards修改。 就像是

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

我得到

21978 * 4 = 87912

backwardsnumberString ,它在內部使用數組。 並且數組從0到size-1進行索引。 因此,此類語句將引發ArrayIndexOutOfBoundsException:

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

在創建字符串時,兩個int均為0,因此在程序執行期間兩個字符串均為“ 0”。 您真正想要的是每次數字更改時字符串都會更改。 因此,您的代碼應更像這樣:

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)

  . . .
}

另外,Java中的數組是零索引的,因此,例如對於字符串“ 10000”,您的程序將在backwards.charAt(5)上使索引超出范圍異常,因為該字符串的索引是從字符0到字符4。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM