Sor*_*ume 0 java foreach loops
这不是'怎么办......' 问题,但'为什么我不能这样做'的问题.
显然,我错过了一些重要的东西(我猜是关于参考),要理解这个问题,如果有人能向我解释它会很好.
我确实找到了之前处理过这个问题的其他帖子,但没有人解释过.
我想为int矩阵的每个元素分配新值.
我有一段这样的代码:
public static void main(String[] args)
{
int[][] tileMatrix = new int[5][5];
System.out.println("New Tile Values:");
for ( int[] tileLine : tileMatrix)
{
for ( int tile : tileLine)
{
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
System.out.println("");
}
System.out.println("Check Values");
for ( int[] tileLine : tileMatrix)
{
for ( int tile : tileLine)
{
System.out.print(tile + " ");
}
System.out.println("");
}
}
Run Code Online (Sandbox Code Playgroud)
这导致:
新平铺值:22 17 29 20 5
12 13 38 35 19
1 9 10 23 27
24 3 36 3 19
37 4 5 18 26
检查值0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
显然我无法改变这样的价值观.我不知道在foreach循环中是否通常是不可能的,或者我是否只是做错了.我可以用正常的for循环解决我的问题,我知道,但为什么我必须这样做?
增强for循环只接受数组中元素的值并将它们存储在变量中.对于值,这意味着原语的副本或存储在数组中的引用值的副本.如果为此变量重新分配新值,则只需修改此变量的值,而不是数组中的值.
这解释了为什么这个for循环不起作用:
for ( int tile : tileLine) {
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
Run Code Online (Sandbox Code Playgroud)
for上面的陈述表现如下:
for (int i = 0; i < tileLine.length; i++) {
int tile = tileLine[i];
//you modify the local variable tile, not the element in the array
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
Run Code Online (Sandbox Code Playgroud)
如果要修改数组中的值,则应直接在数组中修改该值:
for (int i = 0; i < tileLine.length; i++) {
tileLine[i] = (int) (Math.random() * 39);
System.out.print(tileLine[i] + " ");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
397 次 |
| 最近记录: |