I want to generate a random number of 14 positive digits only and I use the below function for it:
public void random()
{
Random number = new Random();
long l = number.nextLong();
number.setSeed(System.currentTimeMillis());
long num = Math.abs(number.nextInt())%999 + (l/100000); // problematic line
mTextBox.setString("" + num);
}
I very new to to JavaMe, I have made above function myself but I believe it is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 12 or 13 numbers not 14.
Any suggestions or improvement to the code will be highly appreciated.
If you want 14 digits, then you should use 14 calls to number.nextInt(10) - something like this:
public static String randomDigits(Random random, int length)
{
char[] digits = new char[length];
// Make sure the leading digit isn't 0.
digits[0] = (char)('1' + random.nextInt(9);
for (int i = 1; i < length; i++)
{
digits[i] = (char)('0' + random.nextInt(10));
}
return new String(digits);
}
Note that I've made the instance of Random something you pass in, rather than created by the method - this makes it easier to use one instance and avoid duplicate seeding. It's also more general purpose, as it separates the "use the string in the UI" aspect from the "generate a random string of digits".
I don't know whether Random.nextInt(int) is supported on J2ME - let me know if it's not. Using Math.abs(number.nextInt())%999 is a bad idea in terms of random distributions.
I didn't understand what you really want, the code suggests that you want a 3 digit number (%999).
Otherwise you can create a 14 digit number between 1000000000000000 and 9999999999999999 by
long num = 1000000000000000L + (long)(number.nextDouble() * 8999999999999999.0);
note (1 / 100000) is 0 (zero) since it is done by integer division, use (1.0 / 100000.0) for double division
long num = 10000000000000L+(long)(random.nextDouble()*90000000000000.0);
EDIT:
mTextBox.setString(MessageFormat.format("{0,number,00000000000000}",
new Object[] {new Long(num)}));
You are getting negative numbers because Random.nextInt() returns any 32-bit integer, and half of them are negative. If you want to get only positive numbers, you should use the expression Random.nextInt() & 0x7fffffff or simply Random.nextInt(10) for a digit.
Related
I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.
I am trying to generate two 9 digit long random long value in Java using the below code:
for (int i =0;i<2;i++) {
String axisIdStr = Long.toString((long)(System.nanoTime() * (Math.random() * 1000)));
System.out.println("######## axisIdStr "+axisIdStr);
String axId = axisIdStr.substring((axisIdStr.length() -9), axisIdStr.length()) ;
}
But when I run this in windows, i get two different numbers where as when run in mac, I get same two numbers. Why is this happening ?
Can you suggest a better way to generate the long values?
According to your requirement you need to generate 9 digit random numbers. As in the comment suggested you can do it using random.Below I have just given one solution to generate random number between two numbers.
long lowerLimit = 123456712L;
long upperLimit = 234567892L;
Random r = new Random();
long number = lowerLimit+((long)(r.nextDouble()*(upperLimit-lowerLimit)));
You could create an array a[] of int of size 9, and populate with random integers 0-9. Then sum the array up multiplying accordingly.
a[8]*1 + a[7]*10 + a[6]*100 ...
You need to make sure that a[0] only takes digits 1-9 tho...
To get even more random sequence, you Ideally should work on Strings, then you would be able to get 0 on the start position of your random "string", it won't be a number.
Or maybe generate somthing pseudo random and strip last 9 digits out of it.
That's the DIY version of what you could accomplish with what's already out there...
Regards
I want to create a randomly generated 16 digit-number in java.But there is a catch I need the first two digits to be "52". For example, 5289-7894-2435-1967.
I was thinking of using a random generator and create a 14 digit number and then add an integer 5200 0000 0000 0000.
I tried looking for similar problems and can't really find something useful. I'm not familiar with the math method,maybe it could solve the problem for me.
First, you need to generate a random 14-digit number, like you've done:
long first14 = (long) (Math.random() * 100000000000000L);
Then you add the 52 at the beginning.
long number = 5200000000000000L + first14;
One other way that would work equally well, and will save memory, since Math.random() creates an internal Random object:
//Declare this before you need to use it
java.util.Random rng = new java.util.Random(); //Provide a seed if you want the same ones every time
...
//Then, when you need a number:
long first14 = (rng.nextLong() % 100000000000000L) + 5200000000000000L;
//Or, to mimic the Math.random() option
long first14 = (rng.nextDouble() * 100000000000000L) + 5200000000000000L;
Note that nextLong() % n will not provide a perfectly random distribution, unlike Math.random(). However, if you're just generating test data and it doesn't have to be cryptographically secure, it works as well. It's up to you which one to use.
Random rand = new Random();
String yourValue = String.format((Locale)null, //don't want any thousand separators
"52%02d-%04d-%04d-%04d",
rand.nextInt(100),
rand.nextInt(10000),
rand.nextInt(10000),
rand.nextInt(10000));
You can generate 14 random digits and then append at the beginning "52". E.g.
public class Tes {
public static void main(String[] args) {
System.out.println(generateRandom(52));
}
public static long generateRandom(int prefix) {
Random rand = new Random();
long x = (long)(rand.nextDouble()*100000000000000L);
String s = String.valueOf(prefix) + String.format("%014d", x);
return Long.valueOf(s);
}
}
Create a 14 random digit number. with Math.random
Concatenate to it at the begining the "52" String.
Convert the string with Integer.parseInt(String) method
I am creating a random number from 1-100, I was looking at some Stackoverflow questions to look for the proper way and I got confused by the many different suggestions.
What is the difference between using this:
int random= (int)(Math.random()*((100-1)+1));
this:
int random= (int)(Math.random()*(100);
and this:
int random= 1+ (int)(Math.random()*((100-1)+1));
int random = (int)(Math.random()*(x);
This sets random equal to any integer between 0 and x - 1.
int random = 1 + (int)(Math.random()*(x);
Adding 1 to the overall expression simply changes it to any integer between 1 and x.
(int)(Math.random()*((100-1)+1))
is redundant and equivalent to
(int)(Math.random()*(100)
So take note that:
1 + (int)(Math.random()*(x) returns an int anywhere from 1 to x + 1
but
(int)(Math.random()*(x + 1) returns an int anywhere from 0 to x + 1.
I recommend that you use Random and nextInt(100) like so,
java.util.Random random = new java.util.Random();
// 1 to 100, the 100 is excluded so this is the correct range.
int i = 1 + random.nextInt(100);
it has the added benefit of being able to swap in a more secure random generator (e.g. SecureRandom). Also, note that you can save your "random" reference to avoid expensive (and possibly insecure) re-initialization.
The first is equivalent to the second. Both will give a random integer between 0 and 99 (inclusive, because Math.random() returns a double in the range [0, 1)). Note that (100-1)+1 is equivalent to 100.
The third, will give an integer between 1 and 100 because you are adding 1 to the result above, i.e. 1 plus a value in the range [0, 100), which results in the range [1, 101).
I want to create randomally number with 16 digits in java.
I can do it with String and after that convert to Long.
there is other option?
Thanks!
You can use the Java class Random to generate random Longs, like here for numbers up to one million:
final long MAX_NUMBER_YOU_WANT_TO_HAVE = 9999999999999999L;
final long MIN_NUMBER_YOU_WANT_TO_HAVE = 1000000000000000L;
Long actual = Long.valueOf(Math.abs(Float.valueOf(new Random().nextFloat() * (MAX_NUMBER_YOU_WANT_TO_HAVE - MIN_NUMBER_YOU_WANT_TO_HAVE)).longValue()));
If you absolutely need 16 digits (not a number from 0 to 10^17-1)
Random rand = new Random;
long accumulator = 1 + rand.nextInt(9); // ensures that the 16th digit isn't 0
for(int i = 0; i < 15; i++) {
accumulator *= 10L;
accumulator += rand.nextint(10);
}
I might have an off-by-one on the for loop, use i < 16 if need be.
Your reason for wanting 16 digits is probably key here.
If you only want a number possibly as big as the biggest 16-digit number, then use your favored random number generator to generate a random number between 0 and 9 999 999 999 999 999. You can then add leading zeroes as needed to display exactly 16 characters if that's the reason.
If you explicitly want there to be 16 decimal digits and the first one cannot be zero, you can try the same exercise with 999 999 999 999 999 as upper bound instead and add a random digit from 1 to 9 in front (multiply it by a quadrillion and then sum with the other random number, if need be).
There's plenty of other options, but those are probably the most obvious and simple to implement. I'm quite sure there are native facilities in Java for generating random long numbers.