All puzzles
Per page
M
Math.random() ยท Casting

Roll a number in a range

Return a random whole number from low to high, including both.

rollBetween(3, 8) returns one of 3, 4, 5, 6, 7 or 8.

7 strips: M1 to M7

int range = high - low + 1;
M1
}
M2
int roll = (int) r + low;
M3
public static int rollBetween(int low, int high) {
M4
int range = high - low;
M5
return roll;
M6
double r = Math.random() * range;
M7

Answer key: M. Roll a number in a range

Order: M4, M1, M7, M3, M6, M2. Extra: M5

public static int rollBetween(int low, int high) {
	int range = high - low + 1;
	double r = Math.random() * range;
	int roll = (int) r + low;
	return roll;
}

Extra strip: int range = high - low;. For rollBetween(3, 8), high - low is 5, so there are only 5 numbers to pick from (3 to 7). high is never rolled.