开发者

JavaMe: Random number generation of 14 positive digits

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜