2015-11-29 26 views
0

我在做Android應用程序隨機表達式,將執行以下操作:爪哇 - 生成與預先設定的答案

  • 生成隨機數(1-9),並將其保存
  • 生成表達其中的答案是前面的步驟
  • 顯示的表達就可以了「小鍵盤」用數字1到9
  • 等待用戶按下小鍵盤上的一個按鈕,並檢查它是否是正確的
  • 如果用戶選錯了回答產生了相同數量的新的表達之前(步驟2)
  • 如果用戶選擇了正確答案,則轉到步驟1

所以我現在要創建將產生表達的方法:

public class Main { 

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

     int number = rnd.nextInt(9) + 1; 
     String example = expressionGeneration(number); 

     System.out.println(example); 

    } 

    private static String expressionGeneration(int a) { 
     StringBuilder sb = new StringBuilder(50); 
     Random rnd = new Random(); 
     char op = '$'; // to make it initialized and recognize mistakes 
     int x; 
     double y = 0.5; 

     do { 
      int choice = rnd.nextInt(7); 
      x = rnd.nextInt(100); 
      switch (choice) { 
      case 0: 
       y = a + x; 
       op = '-'; 
       break; 
      case 1: 
       y = a - x; 
       op = '+'; 
       break; 
      case 2: 
       y = a * x; 
       op = '/'; 
       break; 
      case 3: 
       x = rnd.nextInt(99) + 1; 
       y = a/x; 
       op = '*'; 
       break; 
      case 4: 
       y = Math.pow(a, 2); // will be changed later to display the result right 
       op = '√'; 
       break; 
      case 5: 
       if (Math.sqrt(a) % 1 == 0) { 
        y = Math.sqrt(a); 
        op = '^'; 
        x = 2; 
       } 
       break; 
      case 6:   //it's a joke 
       if (x == 33) { 
        return "33"; 
       } 
       y = 0.5; //to regenerate if (x != 33) 
       break; 
      } 
     } while ((int) y != y); //to check if y is integer and if no - regenerate 

     sb.append((int) y + "" + op + "" + x + "=" + a); // answer here is just for testing 

     return sb.toString(); 
    } 
} 

它的大部分給了我正是我需要的,例如時間: 「-8 + 11 = 3」,但有時它給這樣的人的例子:

  1. 0 $ 92 = 3
  2. 0 * 40 = 8

我認爲這意味着乘法不工作的權利以及在某些情況下,OP和y的循環不會被初始化,但怎麼可能? 或者,也許你可以建議任何其他算法,將在我的情況下工作。

所以我的問題是:我做錯了什麼,有沒有其他方式做我需要的?

由於

+0

適合我 –

回答

1

當使用兩個整數/分割,結果將總是整數,即使結果存儲在變量是一個double。爲了解決這個問題,你需要明確說明該部門的其中一個數字是double

case 3: 
    x = rnd.nextInt(99) + 1; 
    y = a/(double) x; 
    op = '*'; 
    break;