Evaluating two ints at the same time
What I'm doing is running two different random objects to get two random ints, and then doing an if-else statement to run a different section of code depending on which two random ints are selected. If I set it so that it selects just one random int and then runs an if-else statement based on which single int is selected, it works fine. But I can't get it to evaluate two ints at once. When I try to do this, the code in the if-else statements doesn't run at all.
Here's the code...
Random rnd2 = new Random();
int vehiclecolour = rnd2.nextInt(14);
System.out.println("Vehicle colour: " + vehiclecolour);
Random rnd3 = new Random();
int vehicletype = rnd3.nextInt(6);
System.out.println("Vehicle type: " + vehicletype);
if (vehiclecolour==1 && vehicletype==1)
{
//Run some code
}
else if (vehiclecolour==1 && vehicletype==2)
{
//Run some code
}
else if (vehiclecolour==1 && vehicletype==3)
{
//Run some code
}
This continues for all of the remaining possible combinations of the two random ints. Like I said, if I change the code so that only one random int is evaluated, then it will work fine, but when I run it as above, the code inside the if-else statements doesn't run at all. So what am I doing wrong here?
Also, as a side question - is there any way to get it so that the random int objects won't select 0?
Thanks!
Re: Evaluating two ints at the same time
Hello Sean448!
Quote:
Originally Posted by
Sean448
What I'm doing is running two different random objects to get two random ints, and then doing an if-else statement to run a different section of code depending on which two random ints are selected. If I set it so that it selects just one random int and then runs an if-else statement based on which single int is selected, it works fine. But I can't get it to evaluate two ints at once. When I try to do this, the code in the if-else statements doesn't run at all.
This continues for all of the remaining possible combinations of the two random ints. Like I said, if I change the code so that only one random int is evaluated, then it will work fine, but when I run it as above, the code inside the if-else statements doesn't run at all. So what am I doing wrong here?
If I were you, i would make the random objects return two values(ie 1 and 2), change the if statements to evaluate these four combinations (1-1, 1-2, 2-1, 2-2). If that worked, I would then expand it. This way you will be able to find the bug easier.
Quote:
Originally Posted by
Sean448
Also, as a side question - is there any way to get it so that the random int objects won't select 0?
The nextInt(int n) method returns an int between 0 (inclusive) and n (exclusive).
Therefore you cannot make it not select 0. But you can add 1 to the value it returns. For example, if you want a random int between 1 and 6 you can have the following statement:
int x = 1 + random.nextInt(6);
Hope it helps.