Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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 程序的数字输出不符合预期_Java_Arrays - Fatal编程技术网

Java 程序的数字输出不符合预期

Java 程序的数字输出不符合预期,java,arrays,Java,Arrays,代码看起来正确,但它的工作方式与我预期的不同: 示例运行1: 用二进制填充5个元素的数组?1-是,0-否:1 已生成数组:0 1 0 0 示例运行2: 用二进制填充5个元素的数组?1-是,0-否:0 生成的数组:9 8 2 1 守则: public static boolean Q1(int a) { if (a == 1) return true; return false; } public static void main(String[] a

代码看起来正确,但它的工作方式与我预期的不同:

示例运行1: 用二进制填充5个元素的数组?1-是,0-否:1 已生成数组:0 1 0 0 示例运行2: 用二进制填充5个元素的数组?1-是,0-否:0 生成的数组:9 8 2 1

守则:

public static boolean Q1(int a) {
    if (a == 1)
        return true;

    return false;    
} 

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Fill array of 5 elements with binary? (1-yes, 0- no): ");
        int num = s.nextInt();
        int[] Array1 = new int[5];
        if ( Q1(num) == true){
            for ( int i = 0; i<5 ; i++){
                int ran = 0 + (int) Math.random() + (2);
                Array1[i] = ran;
                System.out.print(Array1[i] + " ");

            }

        }
        else 
        {
            for ( int i = 0; i<5 ; i++){
                int ran = 0 + (int) Math.random() + 10;
                Array1[i] = ran;
                System.out.print(Array1[i] + " ");
        }
        }
    }
}
否:假设用户只输入1和0*

我得到这个输出:

用二进制填充5个元素的数组?1-是,0-否:0 101010

改变

(int) Math.random() + 10;
因为Math.random返回0到0.999999,而casting to int总是返回0

返回0到9

另一个是

(int) (2 * Math.random());
返回0或1


一个更好的选择是使用一个随机对象,并对其调用nextInt2表示二进制,或对非二进制整数调用nextInt10。

满是鳗鱼的气垫船是什么意思D@AayKay:最重要的是,您是否了解代码无法工作的原因@ᴍ阿伦ᴍ阿伦:它来自于一个蒙蒂巨蟒喜剧短剧。@HovercraftFullOfEels:是的,它不是生成随机数,它只是生成最后一个number@AayKay不。它只生成10,因为它将[0,1转换为int,始终为0,然后添加10。。
(int) (2 * Math.random());