如何int在特定范围内生成随机值?
我试过以下,但那些不起作用:
尝试1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Run Code Online (Sandbox Code Playgroud)
尝试2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Run Code Online (Sandbox Code Playgroud) 我有一个数字值数组,我想从该数组中随机选择一个值,然后将其插入到一个int变量中.
我不确定你需要看什么代码.所以,
这是for我用来生成13个数字(1-13)并将它们插入数组的循环.
int clubsArray [];
clubsArray = new int [13];
for(int i = 0; i < clubsArray.length; i++) {
clubsArray[i] = i +1;
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但现在我需要从该数组中选择2个随机值(然后将其插入到稍后要使用的变量中).
我在许多网站上环顾四周,我已经看到过ArrayList<String>将数值插入数组然后用于Random generator = new Random()从数组中选择值然后.remove()将其从数组中删除的事情.但是,当我使用它时,它不起作用.
我正在编写一个算术游戏,向用户询问一系列加法问题。然而,我想为每个问题随机分配一个运算符,以便问题可以是:
Question 1: num1 + num2 =
Run Code Online (Sandbox Code Playgroud)
或者
Question 2: num1 - num2 =
Run Code Online (Sandbox Code Playgroud)
我一直在使用 Math.random() 方法对 num1 和 num2 进行随机化,我正在努力解决的最后一件事是随机生成“+”和“-”。
是否与这两个字符的 ASCII 值有关,然后我可以在它们之间随机选择?谢谢您的帮助!
作为旁注,我想请用户“按回车键”开始游戏,但我不知道该怎么做。目前我让用户输入“y”开始。有任何想法吗?非常感谢。
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的代码:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number …Run Code Online (Sandbox Code Playgroud)