简体   繁体   English

用for循环打印数组

[英]printing an array with a for-loop

I've build an array with 10 plurals of 7 and am now trying to print it in reversed order with a for loop. 我用10的7的倍数构建了一个数组,现在尝试使用for循环以相反的顺序打印它。 but my program seems to be ignoring this code. 但我的程序似乎忽略了此代码。 I've no issues printing it in regular order with a for or a for each loop. 我在使用for或for每个循环按常规顺序打印它时没有问题。 What is wrong in this piece of code? 这段代码有什么问题?

int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++) {
     numbers[i] = (int) (Math.random() * 10) * 7;
}
for (int i = numbers.length; i == 0; i--) {
     System.out.println(numbers[i]);
}
System.out.println("---");
for (int i = 0; i < numbers.length; i++) {
     System.out.println(numbers[i]);
}

An array of size N in java has its indexes ranging from 0 to N-1 . Java中大小为N的数组的索引范围是0到N-1 So in fact numbers.length is out of bounds - the last element in numbers is with index numbers.length - 1 . 因此,实际上numbers.length超出范围- numbers的最后一个元素带有索引numbers.length - 1 Also not your condition should be i >= 0 instead of i==0 , otherwise your cycle will never be executed for an array of size greater than 1. 同样,您的条件也不应该是i >= 0而不是i==0 ,否则您的循环将永远不会对大于1的数组执行。

It should be 它应该是

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

in your reverse order loop. 在您的逆序循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM