Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hallo! I need help please in this quation about java programering! Write a stati

ID: 3919657 • Letter: H

Question

Hallo!

I need help please in this quation about java programering!

Write a static method addAtIndex (int [] a, int x, int index) as given an array and an integer, and an index places the integer at the position given by the index value.
NOTE! If specified indexes are taken (a [index]! = 0), all elements in the array with the same or higher index are moved one step to the right (towards the end of the array) so that the specified index becomes available.
If the array is full, the last value in the array will be "thrown"
The index value must not exceed the number of values in the array.
Test the method in a simple application where you call the method a number of times.
Print the array with java.util.Arrays.toString (int []) from the unsuccessful package.

Thanks for help!

Explanation / Answer

Please find the code below.

CODE

==================

import java.util.Arrays;

public class Main

{

   public static void addAtIndex (int[] a, int x, int index) {

       if(index >= a.length) {

           throw new ArrayIndexOutOfBoundsException("Index out of range!!!");

       }

       if(a[index] == 0) {

           a[index] = x;

           return;

       }

      

       boolean isFull = true;

       for(int i=0; i<a.length; i++) {

           if(a[i] == 0) {

               isFull = false;

               break;

           }

       }

      

       if(isFull) {

           throw new ArrayIndexOutOfBoundsException("Array already full. Last element in thar array is " + a[a.length-1]);

       }

      

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

a[i] = a[i-1];

}

a[index-1] = x;

   }

   public static void main(String[] args) {  

       int a[] = new int[5];

       try {

           addAtIndex(a, 15, 3);

           addAtIndex(a, 85, 0);

           addAtIndex(a, 34, 1);

           addAtIndex(a, 12, 2);

           addAtIndex(a, 19, 4);

           //addAtIndex(a, 63, 3);

           //addAtIndex(a, 12, 99);

       } catch (ArrayIndexOutOfBoundsException e) {

           e.printStackTrace();

       }

       System.out.println(Arrays.toString(a));

   }

}