Home > Software design >  Generate a 9 digit Integer in java without repeating the same number
Generate a 9 digit Integer in java without repeating the same number

Time:07-15

I am new to java programming and I am using databases to create a simple Bank Management system. I need to create user accounts with an account number with 9 digits, that does not start with 0. also, all the account numbers must be different. Every time I run the program, it should give me a 9-digit number that is not stored in the 'accounts' table under 'account_number' in the 'login_info' database. Any Idea how to do this? Thank you.

CodePudding user response:

That's how I would do it fad:

Assuming I can ONLY read and write inside the db:

-First, load the numbers of your database inside a new HashSet.

-After that, I would start by counting from the lowest number, to the highest. after each count, I would check in the HashSet whether the number is already existing (if yes, continue counting).

-After finding a number, I would safe the last found number, so you count from the last stand instead of from the beginning next time.

(If you want the number to be absolute random, you also can just roll new numbers instead of counting.)

If you can change something on the db, I would recommend you to set an auto increment option on the number.

CodePudding user response:

If you want the number to be random, create a number from 0 to 899 999 999 and then add 100 000 000 (so the first will never be 0). If the numbers are stored in an Arraylist (in this case called nums), the following code should help:

        int num;
        Do{
            num = (int)(Math.random()*800000000) 100000000;
        }while (nums.contains(num));
        nums.add(num);

CodePudding user response:

For example:

final var digits = IntStream.range(1, 10).boxed().collect(Collectors.toList());
Collections.shuffle(digits);
final var result = digits.stream().reduce(0, (x, y) -> 10 * x   y);
System.out.println(result);
  •  Tags:  
  • java
  • Related