AP CSA 4.9 Debugging: Off the End of the List

Unit 4: Data Collections · Lesson 4.9 · Debugging

Off the End of the List

Traversing ArrayLists. This is not a blank editor: it is someone else's attempt. Find what is wrong, fix it, and submit to be graded against hidden test cases.

Why debugging is its own skill

An ArrayList is indexed exactly like an array, which means the same one-past-the-end mistake is available, and it announces itself with a different exception name that hides the fact that it is the same bug you have already met twice.

What is wrong with it

  1. The traversal uses i <= list.size(), which asks for one index past the last element and throws IndexOutOfBoundsException. Fix the bound.
  2. The running total starts at the first element AND then adds every element including the first, so the first value is counted twice. Start the total at 0.
  3. The largest-value search is correct.

The program reads

A count of at least 1, then that many integers.

The program should print

Every value on its own line, then the sum, then the largest value.

Worked examples

These show what the FIXED program should print. There are more cases you cannot see, and they use different values, so patching around just these numbers will fail.

Example 1 input
4
3 1 4 1
Example 1 output
3
1
4
1
9
4
Example 2 input
1
5
Example 2 output
5
5
5

Your answer

Main.java

Input for the Run button

Run sends whatever is in the code box below, bugs and all, so you can see the crash or the wrong answer for yourself before you fix anything.


  

  

Stuck?

Hint 1

size() for a list is what length is for an array: a count, not a valid index. The last index is always size() - 1.

Hint 2

Seeding an accumulator with the first element only makes sense if the loop then starts at the SECOND one. The max search does exactly that, which is why it is correct. The total does not, so it double counts.

Hint 3

Compare the total loop and the max loop line by line. One starts at 0 with a seed, the other starts at 1 with a seed. Only one of those pairs is consistent.

Where to go next

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]