• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

java, excluding numbers?

mikeE

n00b
Joined
Sep 20, 2004
Messages
6
im still learning java and i want to make a random number generator that exludes zero (0).
i asked my teacher how to do it but she has no clue .... -_-
we're learning how to generate random numbers

Code:
import java.util.Random;

public class RandomNumbers
{
	public static void main(String [] args)
	{
	Random generator = new Random();

	for(int i = 1; i<=5; i++)
		{
			System.out.print(generator.nextInt(5) + " ");
		}
	}
}

i'm trying to make a card game in java ... and i know that cards don't have a 0 card =(


thx, any help will be appreciated :)
 
if the RNG outputs numbers in the range [0,n] and you want [1,n], tell the RNG to give you numbers [0,n-1] and add 1.
 
likewise, you can return a random number in any range you want by using that same logic

ie. random number between 10 and 20

print random(10) + 10;

ie. print random(max - min) + min;

of course that can vary slightly depeding if the random generator includes or excludes the value sent as the parameter
 
Well, since the Random class's nextInt(int n) method generates a number between 0 and n, you should just add 1 to the return value to get a value from 1 to n+1.

Code:
Random rng = new Random() //automatically seeded with a 48-bit number I think
System.out.println(rng.nextInt(12)+1); //prints some 'random' number between 1 and 12.

Is that what you were looking for?

As a note, nextInt(int n) generates a number from (0, n] (0 inclusive to n exclusive, I forget whether I used the correct bracket for each though). This means that if you put in 12, it'd only generate a number between 0 - 11. Adding 1 gets you a number from (1, 12).
 
BillLeeLee said:
As a note, nextInt(int n) generates a number from (0, n] (0 inclusive to n exclusive, I forget whether I used the correct bracket for each though). This means that if you put in 12, it'd only generate a number between 0 - 11. Adding 1 gets you a number from (1, 12).
That would be [0, 12).

Nothing more to add otherwise, just figured I'd address this point real quick.
 
Back
Top