【问题标题】:Incorrect filling tables by foreachforeach 填写的表格不正确
【发布时间】:2017-10-18 14:37:21
【问题描述】:

我必须填写很多表格,所以我制作了表格数组列表。不幸的是,foreach 循环不能正确地增加价值。

private List<int[][]> orgnisms; //field in class
public Organisms(int n_tmp,int m_tmp,int mi_tmp) //constructor
{
 orgnisms= new ArrayList<>();
 newEmptyArrays(); // creates tables 5x5 filled by 0 - works
 randomValues();
}
private void randomValues(){   
    for(int[][] table : orgnisms)               // 10 tables        
    {            

            table[0][0]=1;   // ERROR - should add ONLY to [0][0], but fill other
        }
        for (int[] ii : table) {
            for (int i : ii)
                System.out.print(ii[i]);
            System.out.println();
        }
    }
}

对于点[0][0](如上) - 三个值?:

01111 00000 00000 00000 00000

对于点[1][1],方法添加正确:

00000 01000 00000 00000 00000

【问题讨论】:

  • 你能告诉我们newEmptyArrays吗?
  • 你能告诉我们整个输出吗
  • 最后几行没看懂

标签: java arrays list foreach


【解决方案1】:
for (int[] ii : table) {
    for (int i : ii)
        System.out.print(ii[i]); // <--
    System.out.println();
}

这是错误的。 i,在第二个循环中,不是ii的索引,而是值。

用途:

for (int[] ii : table) {
    for (int i : ii)
        System.out.print(i); // <--
    System.out.println();
}

输出:

10000
00000
00000
00000
00000

【讨论】:

  • 一个很好的例子说明为什么有意义的变量名很重要。
  • @bradimus 是的!也是调试重要性的一个很好的例子:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多