2015-10-30 84 views
-1

每次運行我的程序以獲得兩個隨機生成的整數的總和時,結果總是爲0 + 0.請讓我知道我錯過了什麼。爲什麼我的隨機發生器只產生0的?

public void question() { 

    System.out.println("What is " + Random1 + "+" + Random2 + "?"); 
    userAnswer = scan.nextInt(); 
    System.out.println("You entered: " + userAnswer); 
} 

public void actualAnswer() { 

    Answer = (Random1 + Random2); 

    System.out.println("The Correct Answer is: " + Answer); 

    if(userAnswer==(Answer)) { 
     System.out.println("You answered correctly!"); 
    } 
    else { 
     System.out.println("You answered incorrectly"); 

    } 
} 


private void random1() { 

    Random1 = random.nextInt(10) + 1; 

} 

private void random2() { 

    Random2 = random.nextInt(10) + 1; 

} 
+1

嘗試和避免使用大寫的變量名稱,這是相當混亂。另外,什麼是「random」,「Random1」,「Random2」和「Answer」?您的代碼不顯示。 – fge

+6

因爲在將值分配給「答案」之前,您沒有調用random1()和random2()方法。正如@fge建議的那樣,閱讀Java命名約定。 – Adi

+0

@阿迪謝謝。我用問題的方法給他們打電話,現在正在工作 – Jb1128

回答

0

雖然你的環境是不是對我很清楚,我從你的問題理解是喲無法生成和隨機數。我編輯了一部分,我的解決方案給了你隨機生成的整數的總和。希望這將是一個幫助:)

import java.util.Random; 
import java.util.Scanner; 

public class RandomGenerator { 

    int randomInt1 =0; 
    int randomInt2 =0; 
    Scanner scan=new Scanner(System.in); 
    int userAnswer; 
    int answer; 
    /*public void question() { 

     System.out.println("What is " + randomInt1 + "+" + randomInt2 + "?"); 
     userAnswer = scan.nextInt(); 
     System.out.println("You entered: " + userAnswer); 
    }*/ 

    public void actualAnswer() { 
     answer = (random1() + random2()); 
     System.out.println(" numbers generated are: "+ random1()+", "+random2()); 
     System.out.println("The Sum is: " + answer); 

     /* if(userAnswer==(answer)) { 
      System.out.println("You answered correctly!"); 
     } 
     else { 
      System.out.println("You answered incorrectly"); 

     }*/ 
    } 


    private int random1() { 
      Random randomGenerator = new Random(); 
      for(int i =0; i<3; i++){ 

      randomInt1 = randomGenerator.nextInt(10); 
      } 
      return randomInt1; 
    } 

    private int random2() { 

     Random randomGenerator = new Random(); 
     for(int i =0; i<3; i++){ 

      randomInt2 = randomGenerator.nextInt(10); 

     } 
     return randomInt2; 
    } 
public static void main(String a[]){ 
    RandomGenerator rg=new RandomGenerator(); 
    rg.actualAnswer(); 
} 
} 
相關問題