a12b23c34 a12b23c34 -4 years ago 70
Java Question

Printing Arrays/Reverse Array

So I have a question regarding printing arrays. These methods receive data from an array created from a file. The output should be 10 integers long in every row for as many integers are contained in the file. Let's say that the file contains {0, 1, 2, 3, 4, 5}, the output should be:

0 1 2 3 4 5


The first method works completely fine. The second method returns an error which I'll include down below. Can anyone help me figure out what's wrong? I've tried googling it but still don't understand. Here's the code:

public static void printArray(int[] array){
System.out.println("Printing array: ");
for (int i = 1; i<array.length+1; i++){
System.out.printf("%7d", array[i-1]);
if (i%10==0){
System.out.println();
}

}
System.out.println();
}
public static void reverseArray(int[] array){
System.out.println("Printing reversed array: ");
int a=0;
for (int i = array.length; i>-1; i--){
System.out.printf("%7d", array[i]);
a++;
if (a%10==0){
System.out.println();
}
}
System.out.println();
}


Here's the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Paniagua_ArrayProcessing.reverseArray(Paniagua_ArrayProcessing.java:49)
at Paniagua_ArrayProcessing.main(Paniagua_ArrayProcessing.java:8)


Thanks for any help! Hopefully it's only a simple problem.

Edit: This is in java btw.

Answer Source

An array goes from 0 to length-1. Change your code to:

for (int i = array.length-1; i>-1; i--){

And the code will work.

You can read more about this here: Java Language Basics: Arrays

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download