我正在尝试创建一个可以生成随机数并指定该随机数可以有多少位的函数。
更具体地说,我正在尝试生成一个长度可能为8、10或12位的数字。该位数由另一个变量指定。
然后我要将此数字表示为字符串中的十六进制或十进制中的有符号和无符号整数。我想我可以只使用该部分的各种Integer.toString方法。
我将如何在Java中生成特定的位长随机数?
到目前为止,我已经安装了此功能框架:
public static String generateQuestion(int numBits, int taskType){
String questionStr = "";
String questionVal = ""; // This is the string hexadecimal version of the randomly generated number
// TODO: Code to generate random value based on numBits
switch(taskType){
case 0: // Hex to Decimal
questionStr = "What are the signed and unsigned values for the " + numBits + "-bit value " + questionVal + "?";
return questionStr; // Return the constructed string
case 1: // Signed Decimal to Hex
case 2: // Unsigned Decimal to Hex
default:
throw new IllegalStateException("Unexpected Question Type: " + taskType); // In case the task type is something other than the 3 possible question types
}
}
答案 0 :(得分:5)
创建一个3
的新实例,整个应用最好只有一个实例。
然后,您可以在其上调用java.util.Random
,其中x是上限(不包括)。因此,如果您想要一个4位随机数,可以调用.nextInt(x)
,或者发现它更具可读性(变成完全相同的字节码),.nextInt(16)
会在0(含)和16(不含),因此从.nextInt(0x10)
到0000
。
要找到'16',只需1111
。例如1 << (bits-1)
将为您提供12位随机数。
数字就是。 rnd.nextInt(1 << (12-1))
没有十六进制,十进制或二进制的概念。那是您在打印时选择的东西。 int
例如将打印String.format("%x", 10)
。