2017-06-05 188 views
-4

我想插入数据到multidementional数组,但'for循环'里面for循环(内部'for循环')不运行(当我运行代码内部循环不runnig唯一其他'for循环')你可以清楚地看到,结果我附加了这个诡计。for循环里面for循环

一些代码:

for(int s=0;s<=y;s++){ //y mean number of arrays, user can input any number for y in here y>=2 
    int w=s+1; 
    System.out.println("number of data for array"+" "+w+':'); 
    int night[][]=new int[s][x.nextInt()]; 
    for(int counter=0;counter<night.length;counter++){ 
     int m=counter+1; 
     System.out.println("insert the number"+m+":"); 
     night[s][counter]=x.nextInt(); 

    } 
} 

我仍然在学习Java请你告诉我,为什么这不是工作

这是结果,当我运行该代码

how much Arrays: 
4 
number of data for array 1: 
6 
number of data for array 2: 
7 
insert the number1: 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
    at practice.Multi_array_data_input.main(Multi_array_data_input.java:42) 
+0

*“不工作”*不是一个适当的问题描述,究竟是什么不工作? – luk2302

+0

预期结果在哪里? – Shinchan

+0

您能否详细说明“不工作”部分? ***它是如何***“不工作”?你有构建错误吗?运行时出现异常?意外的结果?请花一些时间[阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),并学习如何创建[最小,完整和可验证示例](http:/ /stackoverflow.com/help/mcve)。 –

回答

0

的问题是,你调用一个不存在的数组中的索引,因为Java和JavaScript中的数组是基于零的。当您使用int[] array = new int[3]定义数组时,这是否意味着索引0, 1, 2可用。索引3不是数组的一部分。所以为了解决这个问题,当你调用你的夜间数组时,你必须将变量s最小化为1。

for(int s=0;s<=y;s++){ // y mean number of arrays, user can input any number for y in here y>=2 
    int w=s+1; 
    System.out.println("number of data for array "+w+':'); 
    int night[][]=new int[s][x.nextInt()]; 
    for(int counter=0;counter<night.length;counter++){ 
     int m=counter+1; 
     System.out.println("insert the number "+m+":"); 
     night[s - 1][counter]=x.nextInt(); 
    } 
} 
+0

谢谢...............很多................: ) –