我的代码可以随机生成从 000 到 111 的二进制数,但我无法让它创建从 000 到仅 110 的数字。我知道我可以以某种方式重新运行 111 输出的所有代码,但我似乎无法弄清楚如何让它做到这一点。
public String binNumber() {
StringBuilder storage = new StringBuilder();
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage.append(String.valueOf(binny));
i++;
}
return storage.toString();
}
public int giveMeBinary() {
Random rg = new Random();
int bin = rg.nextInt(2);
return bin;
}
最佳答案
更好的方法是生成一个 0 到 6(含)的随机数,然后转换为字符串
public String binNumber() {
Random rg = new Random();
int n = rg.nextInt(7);
return Integer.toBinaryString(n);
}
关于java - 尝试随机生成一个从 000 到 110 的二进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091419/