关于java:在几个不同的参数中生成随机数

Generate Random Numbers within several different parameters

每次运行这个程序时,我都会遇到一个逻辑错误,我觉得下面的代码应该完全满足问题的需要,但是输出肯定是错误的。我看不出我做错了什么。

编写一个Java程序(命名为随机数),生成随机数如下。确保正确标记下面每个部分的输出,并在单独的行上打印输出。与上一个程序一样,使用制表符转义字符将输出排列在标签之后。a)30到50(含)之间的随机整数。b)20到-20(含)之间的随机整数。c)介于-20和-60之间(包括-20和-60)的随机整数。d)0.0至15.9999(含)之间的随机浮点数。

这就是我目前为止所拥有的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class RandomNumbers{

public static void main(String[] args) {

    // Part A) Generate a random integer number between 30 and 50 (inclusive)
    System.out.println("a) Random integer between 30 and 50 (inclusive):" +
            30 + (int)(Math.random() * ((50 - 30) + 1)));
    // Part B) Generate a random integer number between 20 and -20 (inclusive)
    System.out.println("a) Random integer between 30 and 50 (inclusive):" +
            (-20) + (int)(Math.random() * ((20 - (-20)) + 1)));
    // Part C) Generate a random integer number between -20 and -60 (inclusive)
    System.out.println("a) Random integer between 30 and 50 (inclusive):" +
            (-60) + (int)(Math.random() * (((-20) - (-60)) + 1)));
    // Part d) Generate a random floating-point number between 0.0 and 15.9999 (inclusive)
    System.out.println("a) Random integer between 30 and 50 (inclusive):" +
           0.0 + (double)(Math.random() * ((15.9999 - 0.0) + 1)));
}}

我的输出是:a)30到50(含)之间的随机整数:3018a)30到50之间的随机整数(含):-207a)30到50之间的随机整数(含):-6014a)30~50(含)之间的随机整数:0.03.7171159220482286你看,这不对。


您需要在添加表达式中添加括号,否则它将被具体化而不是添加。(示例:text+30+1=>text301)在最后一种情况下,不需要添加1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {

    // Part A) Generate a random integer number between 30 and 50 (inclusive)
    System.out.println("a) Random integer between 30 and 50 (inclusive):" +
            (30 + (int)(Math.random() * ((50 - 30) + 1))) );
    // Part B) Generate a random integer number between 20 and -20 (inclusive)
    System.out.println("a) Random integer between -20 and 20 (inclusive):" +
            ((-20) + (int)(Math.random() * ((20 - (-20)) + 1))) );
    // Part C) Generate a random integer number between -20 and -60 (inclusive)
    System.out.println("a) Random integer between -20 and -60 (inclusive):" +
            ((-60) + (int)(Math.random() * (((-20) - (-60)) + 1))) );
    // Part d) Generate a random floating-point number between 0.0 and 15.9999 (inclusive)
    System.out.println("a) Random integer between 0.0 and 15.9999 (inclusive):" +
           (0.0 + (double)(Math.random() * (16)) );
}


你的问题是你没有把计算放在括号里。Java将把表达式中的EDCOX1和0个符号看作字符串连接。

例子:

1
System.out.println("Test"+1+2);

打印Test12,但

1
System.out.println("Test"+(1+2));

打印Test3

因此,在第一个示例中,您将得到3018作为输出,因为它不添加30+18,而是将两个数字都添加到字符串中。

因此,正确的代码将为您提供所需的输出

1
2
System.out.println("a) Random integer between 30 and 50 (inclusive):" +
        (30 + (int)(Math.random() * ((50 - 30) + 1))));