2016-05-13 92 views
0

我一直在嘗試使用for循環來解決這個問題大約3個半小時已經知道他們可能不會工作,但無法想象更好的方式。獲取一個隨機數組的索引,然後使用相同的索引來打印另一個數組

基本上是:一個隨機數與此產生:

public static int[] toll = {100, 150, 200, 350, 900}; 
public static int[] tollId = {1, 2, 3, 4, 5}; 

public static int randomToll() { 
    int random = new Random().nextInt(toll.length); 
    thisObject = toll[random]; 
    return thisObject; 
} 

public static void print() { 
    System.out.println(tollId[*ThisIndexEqualToRandomIndexFromToll*]); 
} 

現在我想要得到的隨機數的數組或「的thisObject」的索引,而的話,我想該索引來進行設置到打印的收費標識的相同索引,希望這是有道理的。我真的無法想出如何編寫它,如果有更好的方法,然後使用數組,請讓我知道。

+0

我應該澄清一點:實質上,如果100被選爲隨機數,我想打印tollId [0]等等。我知道我可以添加if/else語句,但有一個更好的方法來做到這一點。 –

+2

**爲什麼**不直接從「收費」中隨機獲取索引? 'tollId'的***點是什麼? –

+0

這就是我所需要的,就像我說的,如果有比使用數組更好的方式,請讓我知道。 –

回答

0

我會稍微反轉邏輯。獲取索引,然後您可以在未來點檢索收費。當第二個數組只是一個數字(當然,索​​引+ 1,但可以添加到輸出中)時,不需要跟蹤兩個數組。

public static int[] toll = { 100, 150, 200, 350, 900 }; 

// get the location for the random toll 
public static int randomTollId() { 
    // will return an index between 0 and the # of tolls 
    return new Random().nextInt(toll.length); 
} 

public static void print() 
{ 
    int idx = randomTollId(); 
    System.out.println("The index of " + idx + " has a toll of " + toll[idx]); 
} 
相關問題