【问题标题】:java foreach changes elements [duplicate]java foreach更改元素[重复]
【发布时间】:2017-09-19 18:16:15
【问题描述】:

我尝试使用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

【问题讨论】:

  • 在第二个for中,j是一个值而不是一个索引,尝试只打印j:System.out.print(j + " ");
  • 是的,成功了!谢谢!

标签: java arrays foreach


【解决方案1】:

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

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

【讨论】:

  • 是的,它有效!谢谢)
【解决方案2】:
    System.out.println("*** Sorted array \"foreach-loop\" ***");
    // printing values in console with foreach-loop
    for(int j : myArray) {
        System.out.print(myArray[j] + " "); <---
    }

问题出在这一行,您从数组j 中获取元素,但不是打印它,而是使用它再次访问数组。你的打印声明应该是

System.out.print(j + " ")

【讨论】:

    【解决方案3】:

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

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

    用这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-25
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2020-02-25
      • 2016-06-17
      • 2013-02-26
      相关资源
      最近更新 更多