通过元素的数组中向后循环 [英] Looping through the elements in a array backwards

查看:106
本文介绍了通过元素的数组中向后循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code:

int myArray[]={1,2,3,4,5,6,7,8};

for(int counter=myArray.length; counter > 0;counter--){
    System.out.println(myArray[counter]);
}

我想打印出数组降序排列,而不是按升序排列(从阵列到第一的最后一个元素),但我只是抛出这个错误:

I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at task1.main(task1.java:14)

这是怎么回事?我希望,通过使用myArray.length柜台设置为8,code将只打印出数组的第8元素,然后继续打印前的一个。

Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.

推荐答案

在Java中的数组是由 0 索引到长度 - 1 ,而不是 1 长度,因此,你应该相应地分配你的变量,并使用正确的比较运算符

Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.

您循环应该是这样的:

for(int counter=myArray.length - 1; counter >= 0;counter--){

这篇关于通过元素的数组中向后循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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