java - 为什么不能反向打印?

标签 java arrays for-loop indexoutofboundsexception

我有一个非常简单的问题,但我似乎无法解决它。我在此代码中遇到越界错误

int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length ; i >= -1; i--)
{
   System.out.println(array[i] +" ");
   c++;
   if(c == 10) 
   {
       System.out.println();
       c=0;
   }
}

这是怎么回事?

最佳答案

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

错误,数组从索引 0 开始,因此“length”数组是从索引 0 到索引“length - 1”

所以你的代码是错误的,你应该使用

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

关于java - 为什么不能反向打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448921/

相关文章:

php - 从多维数组创建数组

javascript - Javascript for 循环中的 for 循环

java - java中ArrayList的for循环

javascript - 有没有更有效的方法来设置 p5.graphics 像素数组等于另一个使用 JavaScript 中的 p5.js ?

javascript - 数组推送内数组的 angularjs 动态标签名称

php - 使用 PHPExcel 循环工作表

java - 如何在 CrudRepository 上使用 findAll() 返回 List 而不是 Iterable

java - 使用 getClassLoader() 解析 .properties 文件

java - 计时器和排行榜

java - 使用 java jsoup 登录在网站 rotowire 上不起作用