使用java创建一个4位随机数,数字不重复 [英] Creating a 4 digit Random Number using java with no repetition in digits

查看:470
本文介绍了使用java创建一个4位随机数,数字不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用java写了一个代码来创建一个没有重复数字的随机4位数字,我写的代码如下:-

I wrote a code using java to create a random 4 digit number with no repetition of digits, the code I wrote is given below :-

Random r = new Random();
d1 = r.nextInt(9);
d2 = r.nextInt(9);
d3 = r.nextInt(9);
d4 = r.nextInt(9);
while(d1==d2||d1==d3||d1==d4||d2==d3||d2==d4||d3==d4)
{
    if(d1==d2||d2==d3||d2==d4)
    {
        d2 = r.nextInt(9);
    }
    if(d1==d3||d2==d3||d3==d4)
    {
        d3 = r.nextInt(9);
    }
    if(d1==d4||d2==d4||d3==d4)
    {
        d4 = r.nextInt(9);
    }
}   
System.out.println(d1+""+d2+""+d3+""+d4);


这里是测试用例(从 System.out.println(R1+""+R2+""+R3+""+R4); 生成)如下:-


here are the test cases(generated from System.out.println(R1+""+R2+""+R3+""+R4);) are as following :-

 0123 |  OK as required
 1234 |  OK as required
 2123 |  not OK because 2 is present more than one time 
 9870 |  OK as required
 0444 |  not OK because 4 is present more than one time


现在我的问题是,如果有更好的方法来做到这一点.如果我可以以某种方式增强它?


Now My question here is, that if there is some better way to do this. If I could enhance it in some way?

推荐答案

创建一个从 0 到 9 的整数列表,将其打乱并提取前 4 个.

Create a list of integers from 0 to 9, shuffle it and extract the first 4.

public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>();
    for(int i = 0; i < 10; i++){
        numbers.add(i);
    }

    Collections.shuffle(numbers);

    String result = "";
    for(int i = 0; i < 4; i++){
        result += numbers.get(i).toString();
    }
    System.out.println(result);
}

正在进行一些丑陋的字符串到整数的转换,但你明白了.根据您的用例,您可以看到需要什么.

There's some ugly string-to-int conversing going on, but you get the idea. Depending on your use case you can see what is needed.

这篇关于使用java创建一个4位随机数,数字不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆