0

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;
        }
Temmie
  • 127
  • 2
  • 14
  • you could use an if statement that compares the random number to the current floor. if they are equal, generate another random number until they are not equal. – ethan codes Sep 19 '16 at 03:32

2 Answers2

3

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);
Kelvin
  • 574
  • 3
  • 13
  • 2
    If you change your nextInt(3) to nextInt(4) I think this is the best answer out of all. Remember nextInt generates a number between 0 (inclusive) and n (exclusive). – Amin J Sep 19 '16 at 03:51
0

mya be it could work :-

public int generator(int currentFloor){
    int result = currentFloor;
    while(result == currentFloor){
        result = 1 + (int)(Math.random() * (5 - 1));
    }
    return result;
}
Vishal Goyal
  • 193
  • 14
  • this seems like a good choice. can I ask why you add one to result though? this could potentially put you out of the needed range, right? – ethan codes Sep 19 '16 at 03:42
  • You forgot to cast your result this won't compile – Kelvin Sep 19 '16 at 03:46
  • 1
    @ethancodes: thanks for appreciation. There are many ways to generate random numbers within a specific range. One approach is to use `Min + (Math.random() * (Max - Min))` . There are too many good options available, but I prefer this one. To understand more kindly visit http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range – Vishal Goyal Sep 19 '16 at 03:48
  • You shouldn't need a while loop for this! Kelvin's answer is the way to go. – Amin J Sep 19 '16 at 03:53
  • yes @AminJ, you are right. Kelvin' answer is a good way to go. All can be done within a single if statement. – Vishal Goyal Sep 19 '16 at 03:58