2016-04-21 121 views
-1

我試圖添加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; 
    } 
} 
+0

它以什麼方式不起作用? –

+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)); 
    } 

} 
+0

我如何輸入這個沒有得到錯誤? –

+0

@ Brandon.O,你是什麼意思「輸入這個」? – KevinO

+0

當我把它放到我的程序中時,它說錯誤,它說找不到符號Random r = new Random(); –

0

您需要導入java.util.Random;我會將邏輯提取到方法。喜歡的東西,

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); 
    } 
} 

按照慣例,Java變量名稱以小寫字母。

+0

如果沒有答案,我會如何做到這一點。所以基本上讓用戶自己輸入答案。 –

+1

這聽起來像是一個不同的問題;我建議你從循環開始,不要忘記'import java.util.Scanner' –