Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java.lang.ArrayIndexOutOfBoundsException:循环打印数组很简单_Java_Arrays - Fatal编程技术网

java.lang.ArrayIndexOutOfBoundsException:循环打印数组很简单

java.lang.ArrayIndexOutOfBoundsException:循环打印数组很简单,java,arrays,Java,Arrays,我有一个简单的for循环,它打印整数数组的内容。它不断抛出java.lang.ArrayIndexOutOfBoundsException异常。我已经挠了几个小时的头,不知道我做错了什么 public class ReverseArray { public static void main(String[] args) { int[] nums = {100,90,80,70,60,50,40,30,20,10}; for(int i = 10; i >= 0; i--

我有一个简单的for循环,它打印整数数组的内容。它不断抛出java.lang.ArrayIndexOutOfBoundsException异常。我已经挠了几个小时的头,不知道我做错了什么

public class ReverseArray {
public static void main(String[] args) {

    int[] nums = {100,90,80,70,60,50,40,30,20,10};

    for(int i = 10; i >= 0; i--){
        System.out.print(nums[i] + " ");
    }



   }
 }

由于试图访问10元素数组中的第11个元素,因此引发了
ArrayIndexOutOfBoundsException

数组使用基于零的索引,这意味着当您执行
nums[0]
时,您正试图访问数组的第一个元素。因此:

int[]nums={100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);
将打印

一百

因此,当您执行
nums[10]
操作时,您正试图访问第11个元素,该元素不存在。要解决此问题,可以从索引9开始,而不是从10开始,如:

for(inti=9;i>=0;i--){//“i”以值9开头,因此它可以工作
系统输出打印(nums[i]+“”);
}

大多数编程语言中的数组默认从0索引,因此这意味着第一个元素(100)的索引为0,因此您可以将其作为nums[0]访问。因此,从这个u可以认识到,ur数组中的最后一个元素的索引为9,即nums[9]==10

ur出现此错误是因为ur试图访问第10个索引处的元素,即使ur数组中的元素最多只有第9个索引,即nums[0]=100,nums[1]=90。。。。。nums[9]=10

只要像这样将i改为9,它就会像一个符咒一样工作

public class ReverseArray {
public static void main(String[] args) {

int[] nums = {100,90,80,70,60,50,40,30,20,10};

for(int i = 9; i >= 0; i--){
    System.out.print(nums[i] + " ");
}

}
}

不在“任何编程语言”中-有些语言使用基于1的数组索引,而在其他语言中,默认情况下它可能是基于0的,但具有创建具有非0下限的数组的选项。我认为通常最好坚持使用特定的语句:Java中的数组肯定是0索引的。我认为大多数编程语言中的数组默认使用基于0的索引是您的意思,“most”可能是准确的,是的。谢谢您的更正!