添加随机数

时间:2016-04-21 02:17:44

标签: java random addition

我试图添加2个随机数(1-10),结果必须是正数且没有小数。

这是我想出的。它不会工作,我不知道该怎么做。

public class MathGame {
    public static void main(String[] args) {
       int Low = 1;
       int High = 10;
       Random r = new Random();
       int Result = r.nextInt(High-Low) + Low;
    }
}

2 个答案:

答案 0 :(得分:0)

你可以使用:

Random r = new Random();
int result = 0;
for (int i = 0; i < 2; ++i) {
   result += (r.nextInt(10) + 1);
}

System.out.println(result);

如果您想更清楚具体数字,请尝试:

int num1 = r.nextInt(10) + 1;
int num2 = r.nextInt(10) + 1;

System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));

编辑:在回答后续问题时,此方法会提示用户输入金额

public static void main(String[] args)
{
    Random r = new Random();

    final int MAX = 10;
    // get two random numbers between 1 and MAX
    int num1 = r.nextInt(MAX) + 1;
    int num2 = r.nextInt(MAX) + 1;

    int total = (num1 + num2);

    // display a question
    System.out.printf("What is your answer to %d + %d = ?%n", num1, num2);

    // read in the result
    Scanner stdin = new Scanner(System.in);
    int ans = stdin.nextInt();
    stdin.nextLine();

    // give an reply
    if (ans == total) {
        System.out.println("You are correct!");
    }
    else {
        System.out.println("Sorry, wrong answer!");
        System.out.printf("The answer is %d + %d = %d%n", num1, num2,
                (num1 + num2));
    }

}

答案 1 :(得分:0)

您需要导入java.util.Random;我会将逻辑提取到方法 1 。像,

import java.util.Random;

public class MathGame {
    private static final Random rand = new Random();

    private static int getRandomInt(int low, int high) {
        return rand.nextInt(high - low) + low;
    }

    public static void main(String[] args) {
        int a = getRandomInt(1, 10);
        int b = getRandomInt(1, 10);
        System.out.printf("%d + %d = %d%n", a, b, a + b);
    }
}

1 按照惯例,Java变量名称以小写字母开头。