JAVA 增强的for循环遍历数组

JAVA中遍历数组可以用增强的for循环,语法格式为:

 for(声明语句 : 表达式--要访问的数组名){//代码句子}

如果使用普通的for循环遍历数组,格式如下:

class Variable{public static void main(String[] args) {int[] array1,array2;array1 = new int[] {2,3,5,7,11,13,17,19};//打印array1for(int i=0;i

以上代码输出为: 

2 3 5 7 11 13 17 19 
0 3 2 7 4 13 6 19 

为了少些代码,使用增强的for循环替换以上代码的普通for循环,即

class Variable{public static void main(String[] args) {int[] array1,array2;array1 = new int[] {2,3,5,7,11,13,17,19};//打印array1for(int x: array1) {System.out.print(array1[x]+" ");}}
}

运行报错:5 7 13 19 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 8-------------一种运行时异常,常出现在数组下标越界中,称为下标出界异常

出错的原因是lz脑子抽了把打印语句写错了,正确写法是:

System.out.print(x+" ")


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部