简体   繁体   English

随机生成特定数字

[英]Randomly Generate specific numbers

I want to randomly generate numbers from 1 - 5 but the catch is it should not randomly generate its currentFloor .我想从 1 - 5 随机生成数字,但问题是它不应该随机生成它的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.我的问题是从案例 2 到案例 4。在案例 2 中,它应该随机生成数字 1、3、4 和 5。相同的逻辑适用于案例 3 和案例 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;
        }

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.生成一个介于 1 和 4 之间的数字,如果该数字 >= 到 currentFloor 将其增加 1。这将适用于所有情况,因此您可以在 switch 语句之前计算它。

Actually from your code, if you use this strategy you don't even need the switch statement.实际上从你的代码来看,如果你使用这个策略,你甚至不需要 switch 语句。

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM