打印数组中的每个元素

时间:2016-11-30 19:15:59

标签: java arrays

我练习数组,并且我试图打印出用户输入列表的列表中的每个元素。我在最后一次for循环中遇到了麻烦。我不确定我做错了什么。 *我正在学习java独奏。

public static void main(String[] args) {
    System.out.println("Enter the length of the array: ");
    Scanner input = new Scanner(System.in);
    int length = input.nextInt(); 

    int[] arr; 
    arr = new int[length]; 


    //Asks the user to input values into a list
    for (int counter = 0; counter < length; counter++){
        System.out.println("Enter number into list: "); 
        int number = input.nextInt(); 

        arr[counter] = number;

    }//end of for-


    System.out.println("The list is below: ");
    System.out.printf("%s%8s\n", "Index", "Entry");

    //ERROR: This is where the error occurs!!!!!
    //Displays the list to the user 
    for (int count: arr){
        System.out.printf("%d%8d\n"
                , count, arr[count]);
    }//end of for- 
}//end of main method

编辑:我通过添加公共计数变量修复了我的代码。然后在最后一个for循环中调用该变量,等等。如果PLS LMK有更好的方法!!

3 个答案:

答案 0 :(得分:0)

增强的for循环将遍历值,索引本身将是隐式的,不可访问。

你可能想要这样的东西:

for (int i = 0; i < arr.length: arr++){
    System.out.printf("%d%8d\n", i, arr[i]);
}

...或者如果你想使用增强的for循环:

for (int value : arr){
    System.out.printf("%d\n", value);
}

...但是你没有索引。

答案 1 :(得分:0)

//ERROR: This is where the error occurs!!!!!
//Displays the list to the user 
for (int count: arr){
    System.out.printf("%d%8d\n"
            , count, arr[count]);
}//end of for-

这不正确。假设您有一个值为[1, 2, 300]的数组。您使用代码获得的输出将是:

  • 1, 2
  • 2, 300
  • Index error

这是因为您正在调用arr[count],在我的示例中,计数将变为300,因此您将尝试访问数组中的索引300,它不存在。你在寻找的是:

for(int index : arr) {
    System.out.println(index);
}

这将打印出arr中的所有元素。如果你想打印出索引,然后打印出该索引的相应值,你需要像这样做一个常规的for循环:

for(int i = 0; i < arr.length; i++) {
    System.out.println(i + " " + arr[i]);
}

答案 2 :(得分:0)

这就是你需要改变的全部内容:

for (int count: arr){
    System.out.println(count);          
}

此处的计数实际显示您放入数组的值。

因此,如果您输入了12,13,14作为输入,则此计数将显示12,13和14。

数组的长度是您采用的第一个输入,与数组输入不同。

要打印索引,您可以执行以下操作:

int c =0;
for (int count: arr){
    System.out.println(c);
    System.out.println(count);
    c++;
}
相关问题