-4

I was trying to take three command line arguments as input and do some basic maths operations, but the compiler is showing arrayindex out of bound error in lines having Integer.parseInt().

public class testarray {
        
    public static void main(String args[]) {
    
        int i=0;
        int length,start,increment;
        /*trying to take 3  command line arguments */
        length=Integer.parseInt(args[0]);
        int array[]=new int[length];
        start=Integer.parseInt(args[1]);
        increment=Integer.parseInt(args[2]);
        if(args.length!=3) {
            System.out.println("error");
        }
        else
        {
            for( i=0;i<array.length;i++) {
                array[i]=start+(start+increment);
            }
            System.out.printf("%5d%8d\n","index", "value");
        
            for(i=0;i<=array.length;i++) {
                System.out.printf("%d%d\n",i,array[i]);
            }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

2

In last for loop in your program you have:

for(i=0; i <= array.length; i++)

It should be changed to

for(i=0; i < array.length; i++)

Also I would suggest to check if you pass the arguments the right way (especially when using IDE you have to pass them the way your IDE requires it), because if they are not read correctly it may cause ArrayIndexOutOfBoundsException in your program. I suggest you to firstly print content of arrays to check if they are correctly filled with data you desired to store in them just to make sure everything is done properly.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • im using eclipse IDE.the command line arguments print just fine .is shows the same error on Netbeans. – Pallab Mahata Nov 27 '17 at 17:18
  • also when i pass 2 or any other no. of command line arguments it works fine and prints the first part of if clause and prints "error". – Pallab Mahata Nov 27 '17 at 17:24
  • sorry guys.. i turns out it was a problem related to IDE.and System.out.printf("%5d%8d\n","index", "value"); this line.now its works fine – Pallab Mahata Nov 27 '17 at 17:45
  • Yes, but the line I mentioned will cause ArrayIndexOutOfBoundsException too because in the last loop it will try to make use of array[length] when last index of your array is array[length - 1]. Sooner or later you need to change it too. – Przemysław Moskal Nov 27 '17 at 18:07
0

As you are trying to take three command line arguments then :

array.length = 3 , where indexes run from 0 , 1 and 2.

In last for loop of your program you have :

for(i=0; i <= array.length; i++)

Now , for i = 3 we have 3 <= array.length as true and when you try to access

array[3] in your for loop exception is raised . In order to avoid it

change follow

for(i=0; i < array.length; i++)

ALLEN
  • 1
  • 2