// Program to test solutions to problem #5 on the cse143 midterm, winter 2022. // Fill in your solution to removeLast, then compile and run the program // note: this program doesn't test the exception that should be thrown import java.util.*; class ArrayIntList { public void removeLast(int n) { // fill in your solution here // you can also rename the parameter above } public void removeLast2(int n) { int index = -1; for (int i = 0; i < size; i++) { if (elementData[i] == n) { index = i; } } if (index != -1) { for (int j = index; j < size - 1; j++) { elementData[j] = elementData[j + 1]; } size--; } } private int[] elementData; // list of integers private int size; // current number of elements in the list public static final int DEFAULT_CAPACITY = 100; // post: constructs an empty list of default capacity public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // post: returns true if list is empty, false otherwise public boolean isEmpty() { return size == 0; } // post: creates a comma-separated, bracketed version of the list public String toString() { if (size == 0) { return "[]"; } else { String result = "[" + elementData[0]; for (int i = 1; i < size; i++) { result += ", " + elementData[i]; } result += "]"; return result; } } // post: appends the given value to the end of the list public void add(int value) { elementData[size] = value; size++; } } public class Test5 { private static int testCount, failCount; public static void main(String[] args) { test(3, new int[] {3, 5, 7, 3, 19, 42, 8, 23, 5, 5, 5, 7, 2, -8, 3, 5, -3}); test(3, new int[] {3, 5, 7, 3, 19, 42, 8, 23, 5, 5, 5, 7, 2, -8, 5, -3}); test(3, new int[] {3, 5, 7, 19, 42, 8, 23, 5, 5, 5, 7, 2, -8, 5, -3}); test(3, new int[] {5, 7, 19, 42, 8, 23, 5, 5, 5, 7, 2, -8, 5, -3}); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int n, int[] data) { ArrayIntList list1 = new ArrayIntList(data.length); ArrayIntList list2 = new ArrayIntList(data.length); for (int number : data) { list1.add(number); list2.add(number); } System.out.println("removing " + n); System.out.println("list = " + list1); list1.removeLast2(n); boolean fail = false; try { list2.removeLast(n); } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (!fail) { if (!list1.toString().equals(list2.toString())) { System.out.println("expected list after = " + list1); System.out.println("your list after = " + list2); fail = true; } else { System.out.println("lists after match"); } } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }