Вопрос

I have a very simple problem but I can't seem to solve it. I'm getting an out of bounds error on this code

int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length ; i >= -1; i--)
{
   System.out.println(array[i] +" ");
   c++;
   if(c == 10) 
   {
       System.out.println();
       c=0;
   }
}

What's the deal?

Это было полезно?

Решение

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

wrong, arrays starts at index zero, so a "length" array is from index 0 to index "length - 1"

so your code is wrong, you should use

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

Другие советы

You get an IndexOutOfBounds because you're starting out of the array

int c = 0;
    System.out.println();
    System.out.println("Printing array in Reverse order:");
    for (int i = array.length -1; //HERE
                          i >= 0;//HERE
                          i--) {
      System.out.println(array[i] +" ");
      c++;
      if(c == 10) {
       System.out.println();
       c=0;
      }
    }

In Java, array index go from 0 to "length - 1". So if you start in array.length, you are trying to access out of the array's positions. Same occurs if you try to access to -1 index, because your least index is 0.

Here is a small piece of code which will work you to get the reverse :)

public class newarray {

    public static void main(String args[]){

        int arr[]={10,20,30};
        int size=arr.length;
        for(int i=size-1;i>=0;i--){
            System.out.println(arr[i]);


        }


    }
}

OutPut :

30 20 10

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top