java foreach更改元素

时间:2017-09-19 18:16:15

标签: java arrays foreach

我尝试使用forforeach循环来打印已排序的数组。但我明白,forforeach循环会打印同一个数组的不同值。我无法理解我做错了什么?

以下代码:

import java.util.Random;

class ArraysTest {
    public static void main(String[] args) {

        int[] myArray = new int[20];
        Random rand = new Random();

        System.out.println("*** Unsorted array ***");

        // filling myArray by random int values
        for(int i = 0; i < myArray.length; i++) {
            myArray[i] = (rand.nextInt(i+1));
            System.out.print(myArray[i] + " ");
        } System.out.println("\n");

        // sorting myArray
        java.util.Arrays.parallelSort(myArray);

        System.out.println("*** Sorted array \"for-loop\" ***");
        // printing values in console with for-loop 
        for(int i = 0; i < myArray.length; i++) {
            System.out.print(myArray[i] + " ");
        } System.out.println("\n");

        System.out.println("*** Sorted array \"foreach-loop\" ***");
        // printing values in console with foreach-loop
        for(int j : myArray) {
            System.out.print(myArray[j] + " ");
        }
    }
}

这是控制台:

*** Unsorted array ***
0 1 1 3 3 1 5 1 7 4 2 0 6 11 0 3 7 0 3 17

*** Sorted array "for-loop" ***
0 0 0 0 1 1 1 1 2 3 3 3 3 4 5 6 7 7 11 17

*** Sorted array "foreach-loop" ***
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 3 7

3 个答案:

答案 0 :(得分:4)

您正在访问myArray的第j个元素,实际上j是您要打印的数字。

for(int j:myArray){
    System.out.print(j + " ");
}

答案 1 :(得分:3)

DECLARE @Sql NVARCHAR(MAX);

DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR 
    (SELECT Query 
     FROM VWLetterTYB )

OPEN Cur

FETCH NEXT FROM Cur INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
    --Exec sp_executesql @Sql
    EXEC ('SELECT [sql] = ''' + @Sql + ''', COUNT(*) AS Rowcounts FROM (' + @sql + ') AS t HAVING COUNT(*) > 0 ')

    FETCH NEXT FROM Cur INTO @Sql 
END

CLOSE Cur
DEALLOCATE Cur;

问题在于这一行,您从阵列中获取元素 System.out.println("*** Sorted array \"foreach-loop\" ***"); // printing values in console with foreach-loop for(int j : myArray) { System.out.print(myArray[j] + " "); <--- } ,但不是打印它,而是使用它再次访问阵列。您的打印声明应为

j

答案 2 :(得分:1)

您的问题是,在for-each循环中,您要在索引j处打印值,而您要打印的内容实际上是变量j具有的值。所以替换这个:

for(int j : myArray) {
    System.out.print(myArray[j] + " ");
}

用这个:

for(int j : myArray) {
    System.out.print(j + " ");
}