Java 使用多维数组的math.random
我只是想从动物数组中打印出一个特定的范围。我尝试了3种不同的方法,(提示)我注释掉的代码。print语句总是打印bear。我该如何解决这个问题Java 使用多维数组的math.random,java,arrays,Java,Arrays,我只是想从动物数组中打印出一个特定的范围。我尝试了3种不同的方法,(提示)我注释掉的代码。print语句总是打印bear。我该如何解决这个问题 String animal[][] = { {"bear","lion","wolf","panther"}, {"alligator","komododragon","spyro the dragon","turtle"}, {"great white","clown fish","hammer head
String animal[][] = {
{"bear","lion","wolf","panther"},
{"alligator","komododragon","spyro the dragon","turtle"},
{"great white","clown fish","hammer head","Nessi"},
{"blue jay","red jay","eagle","crow"},
};
int x = (int) Math.random() * (2 - 0);
int y = (int) Math.random() * (4 - 0);
//String yourAniaml = animal[(int) Math.random() * (2-0) ][(int) Math.random() * (4-0)];
// System.out.println(animal[(int) Math.random() * (2-0) ][(int) Math.random() * (4-0)]);
System.out.println( animal[x][y] );
您需要强制转换
Math.random()*foo
的结果,而不仅仅是Math.random()
:
原因是
Math.random()
始终返回范围为0的数字≤ x<1,因此(int)Math.random()
始终是0
,零乘以任何值都是零。假设0,2是x的范围
0,4是你的y的范围
int x = (int) (Math.random() * (2 - 0 + 1)) + 0;
int y = (int) (Math.random() * (4 - 0 + 1)) + 0;
确保在相乘之后而不是之前施法。也不确定为什么要执行
-0
。因此,您可以执行类似于intx=(int)(Math.random()*2)
的操作。
int x = (int) (Math.random() * (2 - 0 + 1)) + 0;
int y = (int) (Math.random() * (4 - 0 + 1)) + 0;