How to create a random number with range? [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 years ago.
I am trying to create a random phone number with a range. The format being (xxx)-xxx-xxx and the area code not starting with 0,8, or 9 and the next set of three being in a range from 100-742 and then the last set of 4 can be any digit. How would i create the first two parts? Any help would be appreciated. Thanks!
import java.util.*;
import java.text.*;
public class PhoneNumber{
public static void main(String[] arg){
Random ranNum = new Random();
//int areaCode = 0;
//int secSet = 0;
//int lastSet = 0;
DecimalFormat areaCode = new DecimalFormat("(000)");
DecimalFormat secSet = new DecimalFormat("-000");
DecimalFormat lastSet = new DecimalFormat("-0000");
//DecimalFormat phoneNumber = new DecimalFormat("(###)-###-####");
int i = 0;
//areaCode = (ranNum.nextInt()); //cant start with 0,8,9
//secSet = (ranNum.nextInt()); // not greater than 742 and less than 100
//lastSet = (ranNum.nextInt(999)) + 1; // can be any digits
i = ranNum.nextInt();
System.out.print(areaCode.format(i));
i = ranNum.nextInt();
System.out.print(secSet.format(i));
i = ranNum.nextInt();
System.out.print(lastSet.format(i));
}
}

well, basically, you need to generate numbers in two ranges
[1; 7]
[100; 742]
To have random integer in range [m; n] you could write:
updated (remove Math.random())
int numberInRange = m + new Random().nextInt(n - m + 1);
HTH

1,2,3,4,5,6,7
makes 7 different values
ranNum.nextInt(7)+1; //So 1 is your lowest number and 7 is the number of different solutions
nexInt will range between 0 and intPassed exclusive,
So ranNum.nextInt(7) will run between 0 and 6, + 1 makes 1 .. 7
This will range between 1 and 7
You can take the same principal for the second range

You can try the next:
int sec = java.util.concurrent.ThreadLocalRandom.current().nextInt(100, 743);
And so on with the other parts of the phone number.
This method returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

Just make a random number greater than 99 and less than 800, then the next would be about the same way.
Random rand = new Random();
// add 1 to make it inclusive
max min
int firstRandomSet = rand.nextInt((799 - 100) + 1) + 100;
//none starts with 0,8, or 9
int secondRandomSet = rand.nextInt((742 - 100) + 1) + 100;
//produces anything from 100-742
to get the numbers 0001 - 9999 you'll have to be creative.
int maxValues= 9999;
int thirdRandomSet = rand.nextInt(maxValues);
System.out.printf("%04d\n", thirdRandomSet);

Related

How can I generate a random number within a certain range with Java? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:
Generate a random number within a certain range (e.g. 5 through 20).
Take the number and store it within a variable.
Perform arithmetic on it.
Here's the code:
import java.util.HashMap;
public class Attack {
public static void main(String[] args) {
HashMap<String, Integer> attacks = new HashMap<String, Integer>();
attacks.put("Punch", 1);
attacks.put("Uppercut", 3);
attacks.put("Roundhouse Kick", 5);
int actionPoints = // Code for random number generation
System.out.println("A brigade integrant appeared!");
System.out.println("What do you do?");
System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
System.out.println("You have " + actionPoints + " Action Points.");
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();
reader.close();
if n == 1 {
System.out.println("The brigade integrant takes 2 HP of damage!");
}
else if n == 2 {
System.out.println("The brigade integrant takes 5 HP of damage!");
}
else if n == 3 {
System.out.println("The brigade integrant takes 8 HP of damage!");
}
}
}
In Java 1.7+ you can do it in one line (not counting the import statement ;):
import java.util.concurrent.ThreadLocalRandom;
int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive
Try this :
int lower = 12;
int higher = 29;
int random = (int)(Math.random() * (higher-lower)) + lower;
There are multiple options for you to generate a random number. Two of these would be:
Math.random(); // Random values ranging from 0 to 1
Random rand; rand.nextInt(x); // Random int ranging from 0 to x
To specify the exact range you could do something like this:
int RandomNumber = Min + (int)(Math.random() * Max);

How to make a random number between -1 and 1 in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
Trying to figure this out for a while, need a random number that is either -1, 0 or 1. Any help would be great.
Random random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(3) - 1;
Will do the work
If you use Java < 8 version then old approach will be great for you:
You can use java.util.Random class and its method nextInt(int bound). This method generates a random integer from 0 (inclusive) to bound (exclusive). If you want some specific range then you will need to perform some simple math operations:
Cut the range: max - min
If you want to include upper bound value then will add 1: nextInt((max - min) + 1) (optional step)
Shift the generated number to the value of lower bound: nextInt((max - min) + 1) + min
Result:
Random r = new Random();
int randomNumber = r.nextInt((max - min) + 1) + min;
If you use Java >= 8 version, then there will be easier approach for you:
Now java.util.Random class provides other methods according to Stream api like:
public IntStream ints(int randomNumberOrigin, int randomNumberBound)
public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound)
Now you can generate a random integer from origin (inclusive) to bound (exclusive) like that:
Random r = new Random();
r.ints(min, max).findFirst().getAsInt();
If you want to include upper bound into generating process then:
r.ints(min, (max + 1)).findFirst().getAsInt();
To prevent producing unlimited stream:
r.ints(min, (max + 1)).limit(1).findFirst().getAsInt();
or
r.ints(1, min, (max + 1)).findFirst().getAsInt();
answer 1
long l = System.currentTimeMillis();
int randomNumber = (int) (l % 3) - 1;
answer 2
int randomNumber = (int) (Math.random() * 3) - 1;
answer 3
Random random = new Random();
int randomNumber = random.nextInt(3) - 1;
Look at this one
Random r = new Random();
int n = r.nextInt((1 - -1) + 1) + -1;
System.out.println(n);
it will generate random between the range you want. output will be 1 or 0 or -1.
You can use int arrays with Random class. Store your values in an integer array, and generate random number for the index of the array.
Sample Code:
final int[] arr = new int[] { -1, 0, 1 };
Random number = new Random();
int n = number.nextInt(arr.length);
System.out.println(arr[n]); //arr[n] will give you random number

Generate a random integer with a specified number of digits Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I ran into this problem today and I'm sure there is an elegant solution I am not thinking of.
Let's say I want to generate a random integer(or long) in Java with a specified number of digits, where this number of digits can change.
I.e. pass in a number of digits into a method, and return a random number with the specified number of digits
Ex.) N = 3, generate a random number between 100-999; N = 4, generate a random number between 1000-9999
private long generateRandomNumber(int n){
/*Generate a random number with n number of digits*/
}
My attempt so far (this works, but it seems messy)
private long generateRandomNumber(int n){
String randomNumString = "";
Random r = new Random();
//Generate the first digit from 1-9
randomNumString += (r.nextInt(9) + 1);
//Generate the remaining digits between 0-9
for(int x = 1; x < n; x++){
randomNumString += r.nextInt(9);
}
//Parse and return
return Long.parseLong(randomNumString);
}
Is there a better/more efficient solution than this?
*There are lots of solutions for generating random numbers in a specified range, I was more curious on the best way to generate random numbers given a set number of digits, as well as making the solution robust enough to handle any number of digits.
I did not want to have to pass in a min and max, but rather just the number of digits needed
private long generateRandomNumber(int n) {
long min = (long) Math.pow(10, n - 1);
return ThreadLocalRandom.current().nextLong(min, min * 10);
}
nextLong produces random numbers between lower bound inclusive and upper bound exclusive so calling it with parameters (1_000, 10_000) for example results in numbers 1000 to 9999.
Old Random did not get those nice new features unfortunately. But there is basically no reason to continue to use it anyways.
public static int randomInt(int digits) {
int minimum = (int) Math.pow(10, digits - 1); // minimum value with 2 digits is 10 (10^1)
int maximum = (int) Math.pow(10, digits) - 1; // maximum value with 2 digits is 99 (10^2 - 1)
Random random = new Random();
return minimum + random.nextInt((maximum - minimum) + 1);
}
You can simply disregard the numbers that are not in the required range. That way your modified pseudo random number generator guarantees that it generates a number in the given range uniformly at random:
public class RandomOfDigits {
public static void main(String[] args) {
int nd = Integer.parseInt(args[0]);
int loIn = (int) Math.pow(10, nd-1);
int hiEx = (int) Math.pow(10, nd);
Random r = new Random();
int x;
do {
x = r.nextInt(hiEx);
} while (x < loIn);
System.out.println(x);
}
}
Here is the way I would naturally write a method like this:
private long generateRandomNumber(int n){
double tenToN = Math.pow(10, n),
tenToNMinus1 = Math.pow(10, n-1);
long randNum = (long) (Math.random() * (tenToN - tenToNMinus1) + tenToNMinus1);
return randNum;
}

How do I get a random number with a negative number in range? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
Consider the following code:
int rand = new Random().nextInt((30 - 20) + 1) + 20
It will return a random number between 30 and 20. However, I need its range to include negative numbers. How would I include negative numbers in the generation?
I have tried using math that would be negative, but that resulted in an error. Simply subtracting or adding the negative numbers would not yield the desired value.
Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;.
To get a random number between a set range with min and max:
int number = random.nextInt(max - min) + min;
It also works with negative numbers.
So:
random.nextInt(30 + 10) - 10;
// max = 30; min = -10;
Will yield a random int between -10 and 30 (exclusive).
It also works with doubles.
You can use Random.nextBoolean() to determine if it's a random positive or negative integer.
int MAX = 30;
Random random = new Random(); // Optionally, you can specify a seed, e.g. timestamp.
int rand = random.nextInt(MAX) * (random .nextBoolean() ? -1 : 1);
Okay. First, try to only create the Random instance once, but for an example,
int rand = -15 + new Random().nextInt(31);
is the range -15 to 15.
The Random.nextInt(int) JavaDoc says (in part) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). Note that your provided example of (30 - 20) + 1 is the range 0 to 10 (inclusive).
As a further example, to get the range 20 to 30 you would use:
int rand = 20 + new Random().nextInt(11);
Remember, the bounds of the result of is 0 to n.
30 - -10. I'm trying to make a survival simulator. That will be my temperature.
Ok. Let's write that range as -10 to 30. nextInt(n) will return a value between 0 and n, so if you want the range below 0 you must subtract 10 from the result and add 10 to the n. That's
Random random = new Random();
int rand = random.nextInt(41) - 10;
Now let's examine how we can determine those numbers. Remember, nextInt() will return between 0 and n (exclusive) and we want -10 to 30 (inclusive); so 41 is n and we subtract 10. If the result is 0 (the min) we get -10, if the result is 40 (the max) we get 30.
int randomNumber=(random.nextInt(DOUBLE_MAX)-MAX);
Alternatively, create a random positive or negative 1 and multiply it.

Java How do I create a random number mod 5?

Java How do I create a random number mod 5 ?
I need only random numbers 0-100, divisible by 5
something like RandomNumber.nextInt(100) % 5
Do this:
int randomMultipleOf5 = 5*random.nextInt(21);
21 is needed to get an integer in the range 0-20 (inclusive). When multiplied by 5 you get a number in the range 0-100 (inclusive).
You can just do:
Random r = new Random();
int randomMultipleOfFive = r.nextInt(21)*5; //generates a number between 0 and 20 inclusive then *5
How about;
int number = RandomNumber.nextInt(21) * 5;
To clarify, nextInt(21) generates a number from 0-20 making 100 a possible generated number, while nextInt(20) would only max generate 95.
int random = new Random().nextInt(21) * 5
Try this:
Random random = new Random();
for(int i=0; i<50; ++i){
System.out.println(random.nextInt(21) * 5);
}

Categories