简体   繁体   中英

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

Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.

I am attempting to take a simple integer ( inputnumber ), convert it to a string ( temp ), create a new int[] array ( numberarray ), and loop through this int[] array, starting from the last digit, and print out the name of the digit.

I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.

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

The Eclipse error message I am getting is:

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

Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1

Therefore, in your for loop, you should change

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

To:

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

Also, as @brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.

Your for loop:

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

You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?

You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.

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

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