最近我开始学习Java,但遇到了很多问题。我尝试在网站上搜索,但似乎无法得到我需要的答案。如果有答案并且错误是我的,我们深表歉意。
请先看一下我的代码:
import java.util.Random;
public class Test {
public static void main (String args[]) {
Random num = new Random();
int[][] multi = new int [3][];
int test = 1; // comments for stackoverflow questions
int test2 = 10; // how can i create something that will range from 1-9?
int test3 = test2-test; // trying this has always generated 0-9 instead
multi[0] = new int [] {num.nextInt(test3), num.nextInt(test3), num.nextInt(test3)};
multi[1] = new int [] {num.nextInt(test3), num.nextInt(10), num.nextInt(10)};
multi[2] = new int [] {test3, test3, num.nextInt(10)};
// PLEASE IGNORE THE 2D ARRAYS, it's just something I am testing on
int rows = 3;
int columns = 3;
for(int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
System.out.print(multi[i][j] + "\t");
}
System.out.println();
}
}
}
我正在尝试模拟大奖,我想在我创建的所有 2D 数组中生成 1 到 9 之间的数字。但是我不知道如何生成1到9之间的数字,我只创建了0-10和0-9范围
我的想法是,一旦我完成了范围1-9的二维数组,那么我可以使用一定数量的if-else语句来让用户只要中心行或对角线行有 3 个相同的数字,即可赢得大奖。
我也尝试过使用:
int test3 = num.nextInt(test2-test+1)-test;
这会生成1-9之间的数字,但如果我全部使用它,它总是会生成相同的数字给我,否则它会因为负数而给出异常。
最佳答案
如果您只想要一个介于 1 和 9 之间的随机数,这应该会有所帮助:
Random r = new Random();
int num = r.nextInt(9) + 1;
关于java - 在二维数组中的 2 个值之间生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29566804/