I would like to generate a ten digit account number greater than 1,000,000,000 and less than 9,999,999,999. I have 3 separate attempts that all are almost operational, but after 9 digits I either receive an error or a number that is generated is not an expected outcome.
for(int i = 0; i < 10; i++) {
int r = rand.nextInt(10);
int l = (int)Math.pow(10,i);
int currentRand = r * l;
System.out.println("i: "+ i+ ", random int: "+ r+", ten to the pow i: "+ l+ ", currentRand: "+ currentRand);
}
int n = rand.nextInt(89999) + 10000;
int n1 = rand.nextInt(89999) + 10000;
int n2 = Math.multiplyExact(n*100000);
System.out.println(n);
System.out.println(n1);
System.out.println(n2);
int accountNum;
String ofNumber = "";
for(int i = 0; i < 10;i++) {
ofNumber += String.valueOf(rand.nextInt(10));
System.out.println(ofNumber);
}
accountNum = Integer.parseInt(ofNumber);
The largest value representable as an int
is 2147483647
, so about 78% of the 10-digit number range is larger than what can be stored in an int
. Use either long
or BigInteger
.
As Jim Garrison says, your account numbers won't fit into an int but they will fit into a long.
The Random class allows you to generate a stream of random long numbers between a minimum (inclusive) and a maximum (exclusive). Here is an example of this that prints out 10 account numbers:
I have assumed that the smallest account number you want is 1000000000 and the largest 9999999999
import java.util.Random;
public class AccountNumberDemo {
public static void main(String[] args) {
Random rand = new Random();
rand.longs(10, 1_000_000_001L, 10_000_000_000L)
.forEach(System.out::println);
}
}
If you just want one account number in a variable, then this shows how to do it:
import java.util.Random;
public class AccountNumberDemo {
public static void main(String[] args) {
Random rand = new Random();
long accountNumber = rand
.longs(1, 1_000_000_001L, 10_000_000_000L)
.findFirst()
.getAsLong();
System.out.println(accountNumber);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.