0

This is the code which I tried to perform Array Left shift operation which works fine for a few inputs but as i am increasing the shift amount it gives an ArrayOutOfBoundException exception.

import java.util.Scanner;

public class ArrayShift {
public static void main(String[] args) {
    int x,y;
    int[] n = new int[10];
    int temp = 0;
    Scanner sc = new Scanner(System.in);
    //x is size of array
    x = sc.nextInt();
    // y is the amount of shift
    y = sc.nextInt();

    for(int i = 0;i<x;i++)
    {
        n[i] = sc.nextInt();

    }
    //Outer forloop for shift amount = y
    for(int k = 0;k<y;k++)
    {
    temp = n[0];

    //Inner forloop for shift amount = 1  
    for(int i=0;i<x;i++)
    {   

        n[i] = n[i+1];


    }
    n[x-1]=temp;
    }

    for(int i=0;i<x;i++)
    System.out.print(n[i]+" ");
  }
  }

Output

20 10
41 73 89 7 10 1 59 58 84 77 77 97 58 1 86 58 26 10 86 51
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at ArrayShift.main(ArrayShift.java:14)
Azim
  • 1,043
  • 13
  • 27
Nishan
  • 133
  • 1
  • 1
  • 5

1 Answers1

0

You are already declaring the size of the array as 10 in this statement:int[] n = new int[10];

which means even if you enter x value as 100 the value of the array size will still be 10. hence the Array Index out of bound exception