简体   繁体   中英

How do i generate a 4-digit pin with no duplicating number

I'm new to android programming and i want to make a 4 Digit PIN generator without any repeats. How do I do it?? I don't know how to loop that very well yet. Thank you!!

I already tried Random but it gives me numbers that repeat.

int randomPIN = (int)(Math.random()*9000)+1000;

String pin = String.valueOf(randomPIN);
dummy.setText(pin);

I'm looking for an outcome of 1354, 4682, 3645 but the results are mostly 3344, 6577, 1988

Create a list of the digits, shuffle it, and return the first four digits. Here's one way of doing it as a static method:

/* No need for a new list each time */
private static final List<Integer> digits =
    new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));

/**
 * Returns a PIN string that contains four distinct digits.
 */
public static String nextPin() {
    Collections.shuffle(digits);
    final StringBuilder sb = new StringBuilder(4);
    for (Integer digit : digits.subList(0, 4)) {
        sb.append(digit);
    }
    return sb.toString();
}

Obviously, if you wanted the digits as an array of numbers instead of a string, you'd process the sublist differently than I've shown here.

If you just return the sublist itself, be aware that it will change each time you

//create list ArrayList numbers = new ArrayList(); Random randomGenerator=new Random();while (numbers.size() < 4) {int random = randomGenerator .nextInt(4); if (!numbers.contains(random)) { numbers.add(random);}}

Somewhat of an academic exercise - here's one requiring Java 8:

    // flag to control if you want number sequence to be the same each run
    boolean repeatable = true;

    // seed for randomness - for permutation of list (not the integers)
    Random rnd = new Random((repeatable ? 3 : System.currentTimeMillis()));

    // generate randomized sequence as a List
    List<Integer> myNums;
    Collections.shuffle((myNums = IntStream.rangeClosed(1000, 9999).boxed().collect(Collectors.toList())), rnd);

    // Work with list...
    for (Integer somePin : myNums) {
        Log.i("", "Next PIN: "+somePin);
    }

You're gonna have to add the random ints step after step and check for duplicates.

Random random = new Random();
int rdmInt = random.nextInt(9);
String pin = "";
while (pin.length() < 4) {
    rdmInt = random.nextInt(9);
    String addition = String.valueOf(rdmInt);
    if (pin.contains(addition)) continue;
    pin += addition;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM