如何生成没有重复号码的 4 位 PIN 码

我是 android 编程新手,我想制作一个没有任何重复的 4 位 PIN 码生成器。我该怎么做??我还不知道如何很好地循环。谢谢你!!


我已经尝试过随机,但它给了我重复的数字。


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


String pin = String.valueOf(randomPIN);

dummy.setText(pin);

我正在寻找 1354, 4682, 3645 的结果,但结果大多是 3344, 6577, 1988


眼眸繁星
浏览 143回答 4
4回答

牧羊人nacy

创建一个数字列表,对其进行打乱,然后返回前四位数字。这是作为静态方法执行此操作的一种方法:/* No need for a new list each time */private static final List<Integer> digits =&nbsp; &nbsp; new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));/**&nbsp;* Returns a PIN string that contains four distinct digits.&nbsp;*/public static String nextPin() {&nbsp; &nbsp; Collections.shuffle(digits);&nbsp; &nbsp; final StringBuilder sb = new StringBuilder(4);&nbsp; &nbsp; for (Integer digit : digits.subList(0, 4)) {&nbsp; &nbsp; &nbsp; &nbsp; sb.append(digit);&nbsp; &nbsp; }&nbsp; &nbsp; return sb.toString();}显然,如果您希望数字作为数字数组而不是字符串,那么您处理子列表的方式将与我在此处显示的方式不同。如果您只返回子列表本身,请注意,每次您返回子列表时,它都会发生变化

料青山看我应如是

有点学术性的练习 - 这是一个需要 Java 8 的练习:&nbsp; &nbsp; // flag to control if you want number sequence to be the same each run&nbsp; &nbsp; boolean repeatable = true;&nbsp; &nbsp; // seed for randomness - for permutation of list (not the integers)&nbsp; &nbsp; Random rnd = new Random((repeatable ? 3 : System.currentTimeMillis()));&nbsp; &nbsp; // generate randomized sequence as a List&nbsp; &nbsp; List<Integer> myNums;&nbsp; &nbsp; Collections.shuffle((myNums = IntStream.rangeClosed(1000, 9999).boxed().collect(Collectors.toList())), rnd);&nbsp; &nbsp; // Work with list...&nbsp; &nbsp; for (Integer somePin : myNums) {&nbsp; &nbsp; &nbsp; &nbsp; Log.i("", "Next PIN: "+somePin);&nbsp; &nbsp; }

慕慕森

//创建列表ArrayList numbers = new ArrayList();&nbsp;随机 randomGenerator=new Random();while (numbers.size() < 4) {int random = randomGenerator .nextInt(4);&nbsp;if (!numbers.contains(random)) {numbers.add(random);}}

素胚勾勒不出你

您必须一步一步添加随机整数并检查是否有重复项。Random random = new Random();int rdmInt = random.nextInt(9);String pin = "";while (pin.length() < 4) {&nbsp; &nbsp; rdmInt = random.nextInt(9);&nbsp; &nbsp; String addition = String.valueOf(rdmInt);&nbsp; &nbsp; if (pin.contains(addition)) continue;&nbsp; &nbsp; pin += addition;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java