Home > Enterprise >  how to fix "Index 10 out of bounds for length 10" [duplicate]
how to fix "Index 10 out of bounds for length 10" [duplicate]

Time:10-01

import java.util.Scanner;

public class arrays3 {
public static void main (String[]args){
    long []a;
    long []b= new long[10]; 
    a= new long[10];
    Scanner inputScanner = new Scanner(System.in); 

    for(int i=0;i<10;i  ){
        System.out.println("Input a number");
        a[i] = inputScanner.nextInt();
    }
        for(int j=0;j<10;j  ){
            b[j]=a[10-j];
            System.out.println("value"   b[j]);
        
        }
    }
}

when running, the output says "exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at arrays3.main(arrays3.java:15)"

CodePudding user response:

below line fails when j=0 that is, it tries to access 10th index where as the array has elements from 0 to 9

 b[j]=a[10-j];

change it to

b[j] = a[(a.length-1) - j]

CodePudding user response:

In the first iteration itself, in b[j]=a[10-j]; the statements becomes b[0]=a[10]; and since the indexes start from 0 and go till 9, this will pop you an error.

You should write

b[j]=a[10-(j  1)];

for proper functioning...

CodePudding user response:

In Java, counting is zero-based, means an array of length 10 would have items from 0 to 9. in the line b[j]=a[10-j], when having j=0, the code would try to get the element in a[10], which is out of index. Try to change it to be b[j]=a[9-j].

For making it more general, you can use length for getting the length of the array: b[j]=a[a.length-1-j]

  • Related