for(int:array)index out of bounds exception

时间:2016-02-27 04:26:20

标签: java

我最近一直在学习Java,今天我遇到了一个问题,我无法找到可行的解决方案。 我的代码如下所示:

public class testTable {

public static void main(String[] args) {
    int bob[] = {456,2,3,4,5,6};

    for(int j : bob) {
        System.out.println(bob[j]);
    }



  }

}

代码始终返回错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 456
at com.Practice.thenewboston.Arrays.Table.testTable.main(testTable.java:9)

任何帮助都会受到赞赏,并且很好地解释了为什么错误发生会很好。 谢谢!

4 个答案:

答案 0 :(得分:0)

通过提供要从中获取值的位置的索引来引用数组。而这些指数从零开始。因此,要从数组中获取第一个值,您将执行bob[0]for-loop正在做的是自动遍历数组的每个元素,并逐个将值放入j。因此,要打印出值,您只需执行System.out.println(j);

答案 1 :(得分:0)

(function() { 'use strict'; var appControllers = angular.module('appControllers', []); appControllers.controller('ProjectsController', ['$scope', '$http', function ($scope, $http) { $http.get('app/json/projects.json').success(function(data){ $scope.projects = data; }); $scope.orderProp = '-year'; }]); appControllers.controller('GalleryController', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.projectId = $routeParams.projectId; }]); })(); 是您正在使用的for循环类型(Enhanced for loop)所需要的。

System.out.println(j);

for(int j : bob) {
        System.out.println(j);
}

答案 2 :(得分:0)

你的循环应该是这样的

  for(int j : bob) {
        System.out.println(j);
    }

这适用于集合

答案 3 :(得分:-1)

  

试试这个......    数组的第一个元素是456,而array length6,因此,您尝试访问array存在的索引。因此,它会导致IndexOutOfBoundException ..

 public class testTable {

public static void main(String[] args) {
    int bob[] = {456,2,3,4,5,6};

    for(int j : bob) {  //this is foreach not for loop be aware.
        System.out.println(j);
    }
  }
}
相关问题