向后循环遍历数组中的元素 [英] Looping through the elements in an array backwards

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

问题描述

这是我的代码:

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,代码只会打印出数组的第 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 中的数组索引从 0length - 1,而不是 1code> 到 length,因此您应该相应地分配变量并使用正确的比较运算符.

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.

你的循环应该是这样的:

Your loop should look like this:

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

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

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