So let's say you want to generate a random number, but you want it to be UNDER a specified amount.
Is this possible?
Random rand = new Random();
int randInt = rand.nextInt( 16 ); //Generates a number in [0, 1, .., 15]
Documentation at:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)
Use the following method random.nextInt(upperBound).
The answers provided here are correct if you are looking for an integer. However, if you are not looking for an integer random number, I think the below solution would work.
If you want a random number between 50 and 100, use this:
randomNumber = 50+(Math.random()*50);
Related
I want to ask how to generate a random number in java , i know it is done by random.nextint() but i want to check if the number is not what i wanted then it should be rejected and a new random number should be generated .
I want something like this :
Integer[] in = {1,2,3,4,5};
int a = new Random().nextInt(10);
for(int i=0;i<in.length ;i++)
if(a==in[i])
//new random number
if the number is present in the above array (in) then new random number should be generated
Just put it in a do-while loop:
int a;
do {
a = new Random().nextInt(10);
} while (Arrays.asList(in).contains(a));
I would avoid not generating a number you didn't want in the first place.
You can do either
int a = random.nextInt(5);
if (a > 0) a += 5;
or use a selection
int[] valid = { 0, 6, 7, 8, 9 }; // 0 to 9 but not 1,2,3,4,5
int a = valid[random.nextInt(valid.length)];
Simply call the method again. That is, if the number generated fits the if criteria then call a = new Random().nextInt(10);
Or, if your for loop ever regenerates a random number, you could just have the if statement do nothing ex: if(xyz){}; which of course would be pointless, and I think the original solution is probably what you seek.
To avoid any loops and retrying, try this:
int [] in = {1,2,3,4,5};
// generate integers from 0 up to the size of your array of allowed numbers:
int index = new Random().nextInt(in.length);
int a = in[index]; // use the random integer as index for your array of allowed numbers
This question already has an answer here:
Select a random value from an Array
(1 answer)
Closed 8 years ago.
I'm writing a program that generates co-primes of a number.
Now for example a number 'A' has 50 co-primes, my objective is to randomly select a co-prime from the list of all co-primes generated for the number A.
Again for example:
consider a number 15, it has co-primes - {1, 2, 4, 7, 8, 10, 11, 13, 14}. So now i have to select randomly from these values. Likewise, if i generate an array of any values, then how to randomly select from this array.
So in general my question is how to generate a random number from the array of numbers that i have. Now, those numbers in the array can be anything. Like not necessarily natural numbers, or prime numbers, etc.
So is there any java function to do so. I've burnt my brain searching the internet, but didn't find one. I usually go for finding result on google, rather than asking quetions on forums. But when one gets exhausted, it's better to ask experts out there who might have faced similar problems.
Thanks in advanced!!
Is that what you want ?
int[] arr = { 1,5,9,3,2,7 };
Random rd = new Random();
int dice = arr[rd.nextInt(arr.length)];
You can use the java.util.Random class for this:
public int chooseRandom(int[] coPrimes) {
//Creates the Random instance
Random randomizer = new Random();
//Generate a random integer between 0 and the length of the array (exclusive)
int value = randomizer.nextInt(coPrimes.length);
//Return the element at that generated index
return coPrimes[value];
}
I can create random numbers from a range using
Random rand = new Random();
int num = rand.nextInt(10);
System.out.println("Generated Random Number between 0 to 10 is : " + num);
But if i need the next random number generated to be a part of the range minus the already generated one, will keeping the above statement in a loop will suffice?
Also I need to stop once i exhaust all the number from the range.
For eg,
The code gives me a random number between [0-10],
1st - 4 - range {[0-10]}
2nd - 9 - range {[0-10]-4}
3rd - 8 - range {[0-10]-4,9}
..
..
10th - 10 - range {[0-10]-[0-9]}
Will this function output from [Range]{this is my requirement} or (Range)? Or is there any better alternative solution?
The easiest way would probably be to:
put the numbers (0 to 10) in a list
call Collections.shuffle() on that list
loop over the list
Something like:
List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 10);
Collections.shuffle(numbers);
System.out.println(numbers);
You can even provide a random generator for the shuffling operation if the default doesn't suit you.
I do not think this is possible. Try to remember the numbers you already generatedin a list and use it to generate more random numbersuntil you find one that is not in your list.
Still fairly new to android. I am trying to learn how to create a random number that has 12 characters, and each time a number is randomly created, it saves to the android database. Please any help with giving me an idea on how to do this would be grateful.
Use
Math.random();
//Complete rnd float between 0 and 1 e.g.
//0.2558734951799192
//0.03857502479001995
//0.08562741500057713
//0.2329257841571789
//0.7471882261881438
or
Random rand = new Random();
int rndNumber = rand.nextInt(49);
//Numbers between 0 and 48
--
So 12 digit random number can be done with both
float random = 100000000000 + Math.random() * 899999999999;
or
Random rand = new Random();
float rndNumber =100000000000 + rand.nextFloat(899999999999)+1;
--
Edited thx to Frizi
You've asked a general question so the best I can do is give you a general answer. You can use the Random class in java to generate your random numbers. For information on how to then store it to a database, chekcout this documentation.
How would you set up a program using Java to generate a 5 digit number using the following statement:
int n = (int)Math.floor(Math.random()*100000+1)
It also has to print the number generated. I have tried writing this different ways and keep coming up with errors.
There are two ways of looking at your problem. Either you need to make sure the random number generator only produces numbers with exactly five digits (in the range 10000 - 99999) or you need to print the numbers with leading 0s when a number is produced that's too low.
The first approach is best met using Java's Random class.
Random rand = new Random();
int n = rand.nextInt(90000) + 10000;
System.out.println(n);
If you're restricted in some way that you must use the statement in your question, then the second approach is probably what you're after. You can use Java's DecimalFormat class to format a random number with leading zeros before printing.
n = (int)Math.floor( Math.random() * 100000 + 1 );
NumberFormat formatter = new DecimalFormat("00000");
String number = formatter.format(n);
System.out.println("Number with lading zeros: " + number);
One might do:
public class Test {
public static void main(String[] args) {
int n = (int)Math.floor(Math.random()*100000+1);
System.out.println(n);
}
}
However, this really isn't the preferred way of generating random integers. Check out the Random class.
Random r = new Random();
for (;;) {
System.out.println(10000 + r.nextInt(90000));
}
A better idea is to generate the number by successively generating 5 random digits. Making the first digit non-zero ensures that the generated number is always 5-digit. I'm posting pseudocode below, it should be easy to convert it into Java code.
A = List(1,2,3,4,5,6,7,8,9)
B = List(0,1,2,3,4,5,6,7,8,9)
output = 0
output=random.choice(A) //first digit from A, no zeros
for i=0 to 4
output=output*10
output=output+random.choice(B) //next digits from B, can have zero
return output
Look up the API docs for Random if you are stuck.
A way to get a random number 00000 - 99999 is to use the following.
Random r= new Random();
// possibly too obtuse for most readers. ;)
System.out.println((""+(100000+r.nextInt(100000))).substring(1));