java - 数组倒计时的反向循环

标签 java arrays for-loop reverse

我收到错误..

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Reverse.main(Reverse.java:20). 

语法没有错所以我不确定为什么编译时会出错?

public class Reverse {

public static void main(String [] args){
    int i, j;


    System.out.print("Countdown\n");

    int[] numIndex = new int[10]; // array with 10 elements.

    for (i = 0; i<11 ; i++) {
        numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
    }

    for (j=10; j>=0; j--){ // could have used i, doesn't matter.
        System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
    }
}

最佳答案

您在 10 个元素 的整数上声明了数组。您正在从 i=0 到 i=10i=10 到 i=0 迭代,这是 11 个元素。显然这是一个索引越界错误

将你的代码改成这样

public class Reverse {

  public static void main(String [] args){
    int i, j;

    System.out.print("Countdown\n");

    int[] numIndex = new int[10]; // array with 10 elements.

    for (i = 0; i<10 ; i++) {  // from 0 to 9
      numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
    }

    for (j=9; j>=0; j--){ // from 9 to 0
      System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?   
    } 

  }
}

Remember indices starts from 0.

.

关于java - 数组倒计时的反向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952645/

相关文章:

java - SAML 编码 opensaml 和 java

python - 有没有办法创建一个可以用作计数器的列表?

python - soc.recv 到底返回什么?

PHP - 更新字段(如果在数组中)

Java 8 Lambdas - 按位与运算

java - 如何以编程方式向应用程序服务器发送远程命令?

java - 一个项目 - 多个程序

java - Java 中的正则表达式帮助

python - 如果不在列表中

C编程自然数加法