为什么我的int []数组循环超出范围? [英] Why is my int[] array loop out of bounds?

查看:116
本文介绍了为什么我的int []数组循环超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告: 对于Java和一般编程人员,我还是很陌生.我会尽量保持清晰.

我试图获取一个简单的整数(inputnumber),将其转换为字符串(temp),创建一个新的int []数组(numberarray),并循环遍历该int []数组,从最后一位数字开始,然后打印出该数字的名称.

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.

我相当确定由于Eclipse调试,从整数到String到int []数组的转换是可行的,但是对于为什么我从Eclipse获得如此简单的for循环的ArrayOutOfBounds消息感到困惑.任何关于我做错事情的线索都值得赞赏.

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

我收到的Eclipse错误消息是:

The Eclipse error message I am getting is:

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

推荐答案

数组在Java中为0索引.这意味着最后一个值位于索引 NUMBER_OF_ELEMENTS-1

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

因此,在您的for循环中,您应该更改

Therefore, in your for loop, you should change

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.

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.

您的for循环:

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

这篇关于为什么我的int []数组循环超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆