Tino APCS

Lab 16.2 Compact

Background

A common task in array processing is to traverse a list and eliminate an undesired value. You will be provided with a text file named compact.txt, which contains non-negative (≥0) integers in random order. The number of integers in the file is not given, but it is no more than 100.

Assignment

  1. Write a program that reads a text file (compact.txt) and stores the integers into both an ArrayList and an array. Do this part in the main method. You are storing into two different types of arrays in order to compare the merits of each type of data structure. ArrayLists are better for certain tasks and arrays are better for others. This lab will help you see some of the pros/cons for each type.

  2. Write a static method compactArray(int[] arr) that "removes" all zeroes from the array passed in. Since it isn't possible to dynamically change the size of an array, we will define "remove all the zeros" as moving the zeros to the end of the array and leaving the front elements compacted together in their original order. See the example below.

    For this part of the lab, you may not use a second array. Doing so is a smart idea, but it eliminates any real need for problem-solving. Along the same lines, do not solve this part of the lab by printing out only the non-zero values in the array. Your compactArray() method must physically move all zeros to the end of the array and keep all non-zero values in the front.

  3. Write another static method compactArrayList(ArrayList<Integer> arr) that literally removes all zeroes from the ArrayList passed in. It is recommended that you use an Iterator for this task.

Instructions

  1. Print out both lists before and after removing the zeros. For example:

    array

    Before: [0, 9, 7, 0, 0, 23, 4, 0]

    After: [9, 7, 23, 4, 0, 0, 0, 0]


    ArrayList

    Before: [0, 9, 7, 0, 0, 23, 4, 0]

    After: [9, 7, 23, 4]

Name your class PX_LastName_FirstName_Compact

You must Sign In to submit to this assignment

Dark Mode

Outline