David Bang David Bang - 4 days ago 7
Java Question

Print each element in an array

I'm practicing arrays, and I'm trying to print out each element of a list that the user inputs into the list. I'm having trouble at the last for- loop. I'm not sure what I'm doing wrong. *I'm learning java solo.

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


EDIT: I fixed my code by adding a public count variable. Then calling that variable in the last for- loop, etc. If there is a better way PLS LMK!!

Answer
//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-

This is not correct. Say you have an array with the values [1, 2, 300]. The output you would get with your code would be:

  • 1, 2
  • 2, 300
  • Index error

This is because you are calling arr[count], in my example count would become 300, so you will try to access index 300 in your array, it doesn't exist. What you are looking for is:

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

This will print out all of the elements in your arr. If you want to print out the index and then the corresponding value at that index you will need to do a regular for loop like so:

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