你可以使用:
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));
}
}
它以什麼方式不起作用? –
當我嘗試編譯它時,我得到錯誤。 –