2016-09-19 29 views
0

我想從1 - 5中隨機產生數字,但捕獲是不應該隨機產生它的currentFloor。我的問題是從殼體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; 
     } 
+0

你可以使用一個,如果該隨機數進行比較,當前樓的說法。如果它們相等,則生成另一個隨機數,直到它們不相等。 –

回答

3

生成1和之間的數4,如果數字大於或等於currentFloor,那麼它將增加1.這將適用於所有情況,因此您可以在switch語句之前計算它。

實際上從你的代碼中,如果你使用這種策略,你甚至不需要switch語句。

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

如果您將nextInt(3)更改爲nextInt(4),我認爲這是最好的答案。記住nextInt會生成一個介於0(包含)和n(不包含)之間的數字。 –

+0

謝謝!有用! – Temmie

0

妙是它可以工作: -

public int generator(int currentFloor){ 
    int result = currentFloor; 
    while(result == currentFloor){ 
     result = 1 + (int)(Math.random() * (5 - 1)); 
    } 
    return result; 
} 
+0

這似乎是一個不錯的選擇。請問爲什麼要添加一個結果?這可能會讓你脫離所需的範圍,對吧? –

+0

你忘了施放你的結果,不會編譯 – Kelvin

+1

@ethancodes:謝謝你的讚賞。有很多方法可以在特定範圍內生成隨機數字。一種方法是使用'Min +(Math.random()*(Max - Min))'。有太多好的選擇可用,但我更喜歡這一個。要了解更多,請訪問http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range –