2016-05-13 96 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]); 
} 
相关问题