Naim Kabir Naim Kabir - 21 days ago 11
Java Question

Printing number in an array backwards

I am new to java and I wondering how I could fix my program which has to take numbers from user input, then store them in an array, and then print those numbers forwards and then backwards. I have managed to get the program to print forward; however, when I try to print it backwards I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at arrays4Days.arrayS1.main(arrayS1.java:55)

import java.util.*;
public class arrayS1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many numbers will you enter? ");
int count = console.nextInt();
int myArray[]= new int [count];

for (int i =0; i < myArray.length ; i++) {
System.out.print("Type a number: ");
int number=console.nextInt();
myArray[i]=number;
}

System.out.println();
System.out.println("Your numbers in forward order:");

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

System.out.println();
System.out.println("Your numbers in backward order:");

for (int i = myArray.length ; i> 0 ; i--) {
System.out.println(myArray[i]);
}

}


}

Answer

Note that in your first loop, i starts at zero and goes up to - but not equals - the length of the array

for (int i = 0 ; i < myArray.length ; i++) {

so the second loop should also start at this position

for (int i = myArray.length - 1; i>= 0  ; i--) {
    System.out.println(myArray[i]);
}

and should go down to zero