簡體   English   中英

為什么我的int []數組循環超出范圍?

[英]Why is my int[] array loop out of bounds?

警告: 我一般對Java和編程都不熟悉。 我會盡量清楚。

我正在嘗試獲取一個簡單的整數( inputnumber ),將其轉換為字符串( temp ),創建一個新的int []數組( numberarray ),並從最后一位開始遍歷該int []數組,然后打印出來數字的名稱。

我相當確定由於Eclipse調試,從整數到String到int []數組的轉換是可行的,但是對於為什么我從Eclipse獲得如此簡單的for循環的ArrayOutOfBounds消息感到困惑。 任何關於我做錯事情的線索都值得贊賞。

    String temp = inputnumber.toString();
    int[] numberarray = new int[temp.length()];

    for (int i=0;i<temp.length();i++) {
        numberarray[i] = temp.charAt(i);
    }


    for (int i=temp.length();i>0;i--) {

        if (numberarray[i]==1) System.out.print("one.");
        if (numberarray[i]==2) System.out.print("two.");
        if (numberarray[i]==3) System.out.print("three.");
        if (numberarray[i]==4) System.out.print("four.");
        if (numberarray[i]==5) System.out.print("five.");
        if (numberarray[i]==6) System.out.print("six.");
        if (numberarray[i]==7) System.out.print("seven.");
        if (numberarray[i]==8) System.out.print("eight.");
        if (numberarray[i]==9) System.out.print("nine.");
        if (numberarray[i]==0) System.out.print("zero");
    }

我收到的Eclipse錯誤消息是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)

數組在Java中為0索引。 這意味着最后一個值位於索引NUMBER_OF_ELEMENTS-1

因此,在您的for循環中,您應該進行更改

int i=temp.length()     // this is last index + 1 (since we are starting from 0)

至:

int i=temp.length() - 1 // this is last index

另外,正如@ brso05所說,不要忘記將循環結束條件更改為i>=0因為最后一個倒退的值將位於索引0。

您的for循環:

for (int i = temp.length(); i >= 0; i--)

您將從temp.length()開始循環。 這不是有效的索引。 也許您想要temp.length()-1?

您應該執行temp.length()-1。原因是數組以索引0而不是1開始,因此數組的最后一個元素以長度-1進行存儲。如果有10個元素,則0-9是您的索引。 如果要擊中所有元素,還可以將i> 0更改為i> = 0。

for (int i=(temp.length() - 1);i>=0;i--) {

暫無
暫無

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

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