Temmie Temmie - 2 months ago 9
Java Question

Randomly Generate specific numbers

I want to randomly generate numbers from 1 - 5 but the catch is it should not randomly generate its

currentFloor
. My problem is from case 2 until 4. In case 2, it should randomly generate numbers 1, 3, 4, and 5. Same logic applies to case 3 and case 4.

switch(currentFloor) {
//generates number from 2-5
case 1:
int destination1 = rand1.nextInt(3) + 2;
destElevator.add(destination1);
System.out.println(destElevator);
break;
case 2:
case 3:
case 4:
//generates number from 1-4
case 5:
int destination2 = rand1.nextInt(3) + 1;
destElevator.add(destination2);
System.out.println(destElevator);
break;
}

Answer

Generate a number between 1 and 4, if the number is >= to currentFloor increment it by 1. This will work for all cases so you can compute it before the switch statement.

Actually from your code, if you use this strategy you don't even need the switch statement.

int destination = rand1.nextInt(4) + 1;
if (destination >= currentFloor) {
    destination++;
}
destElevator.add(destination)
System.out.println(destElevator);
Comments