All puzzles
Per page
T
Constructor ยท Mutator with a condition

Volume with a limit

Write the Volume class: two instance variables, the constructor, up(), then getLevel(). The level starts at 0. up() adds 1 to the level only when the level is below max, the value passed in to the constructor.

After Volume v = new Volume(3); and five calls to v.up(), v.getLevel() returns 3.

17 strips: T1 to T17

public int getLevel() {
T1
}
T2
}
T3
level = 0;
T4
level++;
T5
private int max;
T6
if (level <= max) {
T7
public class Volume {
T8
public Volume(int max) {
T9
}
T10
if (level < max) {
T11
private int level;
T12
}
T13
public void up() {
T14
return level;
T15
this.max = max;
T16
}
T17

Answer key: T. Volume with a limit

Order: T8, T12, T6, T9, T16, T4, T2, T14, T11, T5, T13, T3, T1, T15, T17, T10. Extra: T7

Lines with the same mark can go in either order.

public class Volume {
	private int level;
	private int max;
	public Volume(int max) {
		this.max = max;
		level = 0;
	}
	public void up() {
		if (level < max) {
			level++;
		}
	}
	public int getLevel() {
		return level;
	}
}

Extra strip: if (level <= max) {. With <=, up() still adds 1 when the level is already 3, so the level goes up to 4.