我需要生成一个从 0000 到 9999 的 4 位数字,但我似乎无法这样做。我有这段代码,但有时它会生成 762,我不能让它这样做。我确实需要使用这些方法来生成它。
private java.util.Random rndGenerator = new java.util.Random();
private int randomValue;
public final static int NUMBER_OF_VALUES = 9999;
public GuessRandomValue() {
randomValue = rndGenerator.nextInt(NUMBER_OF_VALUES);
}
public void setAnswer() {
randomValue = rndGenerator.nextInt(NUMBER_OF_VALUES);
}
最佳答案
您只需使用表达式格式化随机值
String.format("%04d", randomValue);
如果 randomValue
为 762,则对 String.format
的调用将根据需要返回“0762”。
编辑:回应下面的评论
请将randomValue
保留为整数。您只想使用此代码进行用户交互,即格式化。因此,要打印randomValue
,您将使用
System.out.printf("%04d\n", randomValue);
如果程序的任何部分需要保留字符串以供用户交互,则应使用String.format
,但无需更改存储randomValue 的方式
.
要比较用户在 randomValue
中输入的内容,您可以使用 Integer.parseInt 。所以你可以使用
int testValue;
try {
testValue = Integer.parseInt(inputLine, 10);
} catch (NumberFormatException ex) {
// The user typed in something that isn't a number. Alert the user somehow, and make
// him or her try again
}
获取 int 形式的输入值,然后将 testValue
和 randomValue
与 == 进行比较。
关于java - 生成 0000 到 9999 之间的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844477/