首页 > 解决方案 > 将 3 添加到随机数的开头

问题描述

public static void setIdentificationNumber2(Staff a) {
    if ("Librarian".equals(a.getPosition())) {
        a.setIdentificationNumber(4 + (int) (Math.random() * 999999 + 1));
    } else {
        a.setIdentificationNumber(3 + (int) (Math.random() * 999999 + 1));
    }
}

只是想知道是否有一种方法可以将 3 添加到从该方法生成的任何随机数的开头,格式为 3XXXXXX。任何帮助表示赞赏!

标签: java

解决方案


最简单的解决方案是从您的随机数创建一个字符串,添加"3"到前面,然后将其解析回int

int randomNumber = (int) (Math.random() * 999999 + 1);
int identificationNumber = Integer.parseInt("3" + Integer.toString(randomNumber));
a.setIdentificationNumber(identificationNumber);

如果您的号码必须始终为 7 位数字,那么您可以添加3000000

int randomNumber = (int) (Math.random() * 999999 + 1);
int identificationNumber = 3_000_000 + randomNumber;
a.setIdentificationNumber(identificationNumber);

推荐阅读