Generate an amount of random numbers from a paramter then store them to call in a method later

huangapple 未分类评论45阅读模式
标题翻译

Generate an amount of random numbers from a paramter then store them to call in a method later

问题

我正在尝试生成随机数字,数量由一个参数确定,然后存储这些数字,以便我可以将它们分配给一个唯一的 ID 字段,与一个字符串代码相结合,例如用户输入代码 "HG-" 和数字 4,该方法将输出 HG-3981 或 HG-8394 等。

我的尝试:

public void generateCustomerID(String prefix, int length)
{
    
    for (int i = 0; i == length; i++)
    {
        Random random = new Random();
        int rand = random.nextInt((9 - 1) + 1) + 1;
        
    }
    System.out.println(prefix + "-" + length);
}
英文翻译

I am trying to generate random numbers the amount determined by a paramter then store these numbers so i can assign them to a uniqe id field combined with a string code before e.g user inputs code "HG-" and the number 4 the method will output HG-3981 or HG-8394 etc

My attempt

    {
        
        for (int i = 0; i == length; i++)
        {
            Random random = new Random();
            int rand = random.nextInt((9 - 1) + 1) + 1;
            
        }
        System.out.println(prefix + "-" + length);
    }


</details>


# 答案1
**得分**: 0

Sure, here's the translation:

不应该打印 `length`,你应该打印 `rand` 变量。

*示例:*

```java
System.out.println(prefix + "-" + rand);

希望这有所帮助!

英文翻译

Instead of printing the length, shouldn't you be printing the rand variable?

Example:

System.out.println(prefix+&quot;-&quot;+rand);

Hope this helped!

答案2

得分: 0

这将生成以 0 填充的长度为 length 的数字整数:

Random rand = new Random();
int length = 6;

DecimalFormat df = new DecimalFormat();
df.setMaximumIntegerDigits(length);
df.setMinimumIntegerDigits(length);
df.setGroupingUsed(false);

for (int i = 0; i < 50; i++) {
    System.out.println(df.format(rand.nextInt((int)Math.pow(10,length))));
}

您需要存储这些数字以确保唯一性。

您可以使用以下任意一种方式来记录已生成的数字:Set<Integer>int[10^length]boolean[10^length]BitSet(10^lenght)。请注意进程重启等情况。

英文翻译

This will generate 0 padded length digit integers:

    Random rand = new Random();
    int length = 6;

    DecimalFormat df = new DecimalFormat();
    df.setMaximumIntegerDigits(length);
    df.setMinimumIntegerDigits(length);
    df.setGroupingUsed(false);

    for (int i = 0; i &lt; 50; i++) {
        System.out.println(df.format(rand.nextInt((int)Math.pow(10,length))));
    }

You will have to store these in order to ensure uniqueness.

You can use any of Set&lt;Integer&gt;, int[10^length], boolean[10^length] or BitSet(10^lenght) in order to record already generated numbers. Be mindful of process restarts etc.

huangapple
  • 本文由 发表于 2020年3月16日 20:55:13
  • 转载请务必保留本文链接:https://java.coder-hub.com/60706414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定