Question 17
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
class Wallet {
private int balance;
private final List<Integer> history = new ArrayList<>();
boolean apply(int change) {
if (balance + change < 0) return false;
balance += change;
history.add(change);
return true;
}
int balance() { return balance; }
int sumOfHistory() { return history.stream().mapToInt(Integer::intValue).sum(); }
}
public class Main {
public static void main(String[] args) {
Wallet w = new Wallet();
int[] changes = {500, -200, -400, 100, -400};
int ok = 0;
for (int c : changes) if (w.apply(c)) ok++;
System.out.println(ok + " " + w.balance() + " " + (w.balance() == w.sumOfHistory()));
}
}
- A 4 0 true Correct
- B 5 -400 true
- C 3 400 true
- D 4 0 false
Correct Answer: Option A
Only -400 at a balance of 300 is refused. Because balance and history change together inside one method, they always agree.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!