2015-04-01 68 views
0

我在編程類中有一項任務。它是這樣的,我必須制定一個程序,用戶需要輸入他想要做的練習。然後,他用1-10的隨機數和隨機算子解決簡單的計算。最後,它應該寫出他得到了多少正確和不正確的。它還應該寫下任務的運行時間。 我做了一些工作,但是當我一個隨機值賦給操作更改隨機運算符或變量

int operation = (int)(Math.random()*3)+1;

或多項a和b

int a = (int)(Math.random()*10); int b = (int)(Math.random()*10);

我總是得到相同數量和運算符時我選擇第二次或第三次我的任務(因爲我使用循環)。有沒有辦法在程序中更改相同的初始化變量或操作符。例如,int a=(int)(Math.Random()*10)在開始時被初始化爲例如3,然後當程序再次循環將其初始化爲不同的數字時,例如6.是否有其他解決方案來解決我的問題? 這裏是我的全部代碼,現在:

import java.util.*; 
    import javax.swing.JOptionPane; 
    public class RandomChar { 


public static void main(String[] args) { 

    char op= ' '; 
    int operation = (int)(Math.random()*3)+1; 

    int a = (int)(Math.random()*10); 
    int b = (int)(Math.random()*10); 
    String s; 
    int correct = 0, incorrect=0; 

    s = JOptionPane.showInputDialog("How many exercises do you want?"); 
    int num = Integer.parseInt(s); 

    long tStart = System.currentTimeMillis(); 

    while(num>0){ 

     if(operation==1) 
     op='+'; 
    else if(operation==2) 
     op='-'; 
    else if(operation==3) 
     op='*'; 

    String str1 = JOptionPane.showInputDialog(a+" "+op+" "+b+" = "); 
    int num1 = Integer.parseInt(str1); 

    if(op=='+'){ 
    if(a+b==num1) 
     correct++; 
    else 
     incorrect++; 
    }else if(op=='-'){ 
     if(a-b==num1) 
      correct++; 
     else 
      incorrect++; 
    }else if(op=='*'){ 
     if(a*b==num1) 
      correct++; 
        else 
      incorrect++; 
    } 
    num--; 
    } 

    long tEnd = System.currentTimeMillis(); 
    long tOverral = tEnd - tStart; 
    double elapsedSeconds = tOverral/1000.0; 
    System.out.println("Correct: "+correct); 
    System.out.println("Incorrect: "+incorrect); 
    System.out.println("Elapsed seconds: "+ elapsedSeconds); 


} 

}

+0

您可以創建一個數字列表,然後調用Collections.shuffle(list);方法,然後訪問從索引0到最後一個索引的列表 – Kartic 2015-04-01 13:59:20

回答

0

只需將隨機數的計算和操作員到你的while循環。其實你計算一次。

while (num > 0) { 
    int operation = (int) (Math.random() * 3) + 1; 

    int a = (int) (Math.random() * 10); 
    int b = (int) (Math.random() * 10); 
    ... 
} 

因此,您在任何練習中都會有新的數字和運算符。