0

The program should print out values stored in an array of size 5 after the user has input the values.

Here is my code:

import java.util.Scanner;

public class Arrays_Qu1 {

  public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);
    int arr[]= new int [5];

    System.out.println("Enter a number");

    int i;
    for (i=0;i<arr.length;i++) {
      arr[i]=sc.nextInt();
    }

    System.out.println(arr[i]);
  }
}

After I enter the 5th value, the program does not terminate but instead throws:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Binary Nerd
  • 13,872
  • 4
  • 42
  • 44
Tia
  • 1,220
  • 5
  • 22
  • 47
  • 4
    What is the value of `i` after the loop? – fmt Sep 15 '16 at 12:56
  • 1
    Debug your code and you'll see that `i` will be 5 after the loop which is out of the index bounds [0,4]. That's because the loop will increment `i` after before checking the condition, i.e. it will increment `i` to 5 and then check `i < arr.length` (i.e. `i < 5`) and terminate the loop - but `i` remains 5. – Thomas Sep 15 '16 at 12:57
  • 1
    The I++ executes one more time than you're thinking; in the last iteration of the loop, right after the array[] assignment. – ABuckau Sep 15 '16 at 12:59
  • @Thomas Thanks, that was a helpful explanation! – Tia Sep 15 '16 at 13:16
  • @Thomas Can you show me how sequence in which this part `for (i=0;i – Tia Sep 15 '16 at 17:36
  • 1
    That should be explained in any decent loop tutorial but basically it is like this: `for( init; condition; increment ) { body; }` results in a sequence like `init, condition check, body, increment, condition check, body, increment, ...` - of course the sequence ends if the condition check fails. :) – Thomas Sep 16 '16 at 07:58
  • @Thomas Thanks, I got it now – Tia Sep 16 '16 at 08:27

2 Answers2

2

Because you are printing outside the loop and it is trying to print arr[5] which is out of bound of the array. The print should be in loop if you want to print each element.

int i;
for (i = 0; i < arr.length; i++) {
    arr[i] = sc.nextInt();
    System.out.println(arr[i]); // to print each element
}

// value of i is now 5, so arr[i] is invalid
System.out.println(arr[i-1]); // to print last element
System.out.println(Arrays.toString(arr)); // to print whole array
Shahid
  • 2,288
  • 1
  • 14
  • 24
0

You should access the last element of the array like:

 System.out.println(arr[i - 1])

but I believe printing just the last element of an array is not what you want. So you should move line

 System.out.println(arr[i])

in a for loop and it should be ok.

peterremec
  • 488
  • 1
  • 15
  • 46