Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用多维数组的math.random_Java_Arrays - Fatal编程技术网

Java 使用多维数组的math.random

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

我只是想从动物数组中打印出一个特定的范围。我尝试了3种不同的方法,(提示)我注释掉的代码。print语句总是打印bear。我该如何解决这个问题

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;