THINK FIRST·CODE LATER

← All labs

IntQueue: an object that manages its own array

Problem

A queue serves its elements in their order of arrival. Write a class IntQueue and a public class IntQueueApp.

IntQueue hides an int[] elements and a counter size.

  • Three constructors: IntQueue() (capacity 4, through this(4)), IntQueue(int capacity) and the copy constructor IntQueue(IntQueue other), which must give the new queue its own array.
  • enqueue(int v) adds at the end; when the array is full, it is replaced by one twice as long.
  • dequeue() removes and returns the first element and shifts the others one place forward.
  • peek(), isEmpty(), getSize(), getCapacity().

main reads the commands add 5, remove, first, size until the end of the input. Then it makes a copy of the queue, empties the copy while printing it, and shows that the original is intact. For the input

add 5
add 8
add 2
size
remove
first
add 9
add 4
add 7
size

the program prints

Size 3, capacity 4
Removed 5
First is 8
Size 5, capacity 8
Remaining, first to last: 8 2 9 4 7
Original still holds 5 element(s); the copy holds 0

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l11-8-data-1.txt

add 5
add 8
add 2
size
remove
first
add 9
add 4
add 7
size
What your program must print for l11-8-data-1.txt
Size 3, capacity 4
Removed 5
First is 8
Size 5, capacity 8
Remaining, first to last: 8 2 9 4 7
Original still holds 5 element(s); the copy holds 0

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l11-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l11-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.