CS174: OOP - Drills - Array Insert
Developed by Professor Tralie and Professor Mongan.
Exercise Goals
The goals of this exercise are:- To do proper array indexing
- To use loops in concert with arrays
- To allocate and populate new arrays
insertElement
method in ArrayUtils.java
to insert an element at a particular index. For example, if you have the array {0, 5, 4, 8, 2}
and you insert the element 1
at index 2
, you should create a new array with the elements {0, 5, 1, 4, 8, 2}
. NOTE: The tediousness of this seemingly simple operation is what motivates us to use other data structures such as an ArrayList
or linked list.
Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is ctralie
(non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit)
Netid |
ArrayUtils.java
public class ArrayUtils {
/**
* Creates and returns a new array with "element" at the index "index," and
* everything after the original index shifted over to the right by one
*
* @param arr The original array
* @param index The index at which to place the new element. Should be a value less
* than the length of the array
* @param element The value of the new element
*
* @return An array with the new element inserted
*/
public static int[] insertElement(int[] arr, int index, int element) {
/** TODO: Fill this in. You should return
* an int representing the number of zeroes in the
* array arr
*/
int[] newArray = {}; // This is a dummy value. You should change this
return newArray;
}
/**
* Prints out the elements of an array, separated by commas
*
* @param arr The array to print
*/
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length-1) {
System.out.print(",");
}
}
}
}
Tester.java
public class Tester {
public static void main(String[] args) {
int[] arr0 = {0, 5, 4, 8, 2};
int[] result0 = ArrayUtils.insertElement(arr0, 2, 1);
int[] result1 = ArrayUtils.insertElement(arr0, 4, 10);
int[] result2 = ArrayUtils.insertElement(arr0, 0, 50);
ArrayUtils.printArray(result0);
System.out.print(".");
ArrayUtils.printArray(result1);
System.out.print(".");
ArrayUtils.printArray(result2);
}
}
Tester.main(null);