THINK FIRST·CODE LATER

← All labs

Make your list work in a for-each loop

Problem

for (E e : list) works on any class that implements Iterable<E>. In IterableList, write a singly linked list Chain<E> implements Iterable<E> with add, size, toString and

public Iterator<E> iterator()

returning an object of a private inner class that implements hasNext(), next() and remove():

  • next() throws a NoSuchElementException("no more elements") at the end;
  • remove() deletes the element returned by the latest next(), and throws an IllegalStateException("call next() before remove()") if there is none.

main reads integers, then: prints the list; sums it with a for-each loop; removes the even numbers through an iterator; adds 100 at the end; and finally provokes both exceptions. For the input

4 7 10 3 8 8 5

the program prints

List: [4, 7, 10, 3, 8, 8, 5]
Sum with for-each: 45
After removing 4 even number(s): [7, 3, 5], size 3
After adding 100 at the end: [7, 3, 5, 100]
Asking a finished iterator: no more elements
remove() first: call next() before remove()

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.

d10-9-data-1.txt

4 7 10 3 8 8 5
What your program must print for d10-9-data-1.txt
List: [4, 7, 10, 3, 8, 8, 5]
Sum with for-each: 45
After removing 4 even number(s): [7, 3, 5], size 3
After adding 100 at the end: [7, 3, 5, 100]
Asking a finished iterator: no more elements
remove() first: call next() before remove()

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 < d10-9-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-9-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.