2013-08-22 36 views
0

這是一個相當愚蠢的問題,但我無法解決它(可能是因爲一天結束)。如何組合類?

  • 目前,我有3類:MainMathTaskTask
  • 從主要我提供的參數:級別,數量。
  • 我想收到:a,b,回答,操作。

我就是這麼做的:

MathTask mt = new MathTask(level, count); 
     Task t = mt.getNewTask(); 

MathTask:

public class MathTask { 
    int level; 
    int answer; 
    int count; 

    public MathTask(int level,int count){ 
     this.level=level; 
     this.count=count; 
    } 
    public Task getNewTask() { 
     int range = (int) Math.pow(10, level); 

     int a = getRandomInt(0, range); 
     int b = getRandomInt(0, range); 
     String operation = ""; 
     int sw = getOperation(); 

     switch (sw) { 
     case 0: 
      // sum 
      answer = a + b; 
      operation = "+"; 
      break; 
     case 1: 
      // substruct 
      answer = a - b; 
      operation = "-"; 
      break; 
     case 2: 
      // multiply 
      answer = a * b; 
      operation = "*"; 
      break; 
     case 3: 
      // divide 
      answer = a/(++b); 
      operation = "/"; 
      break; 
     default: 
      break; 

     } 
     return new Task(a, b, answer, operation); 

    } 
    public int getOperation() { 
     if (count < 5) 
      return 0; 
     else if (count > 4 && count < 10) 
      return 1; 
     else if (count > 9 && count < 15) 
      return 2; 
     else if (count > 14 && count < 20) 
      return 3; 
     return 0; 
    } 
    public int getRandomInt(int from, int to) { 

     return from + (int) (Math.random() * ((to - from) + 1)); 

    } 
} 

任務

public class Task { 
    private int a; 
    private int b; 
    private int answer; 
    private String operation; 

    public Task(int a, int b, int answer, String operation) { 
     this.a = a; 
     this.b = b; 
     this.answer = answer; 
     this.operation = operation; 

    } 

    public int getA() { 
     return a; 
    } 

    public int getB() { 
     return b; 
    } 

    public void setB(int b) { 
     this.b = b; 
    } 

    public int getAnswer() { 
     return answer; 
    } 

    public String getOperation() { 
     return operation; 
    } 
} 

能不能做到更好?如何結合MathTaskTask保持功能?

+0

什麼是'resice'? –

+0

對不起,這是'recieve' – Yarh

+2

這屬於http://codereview.stackexchange.com/ –

回答

0

設置爲getNewTask,getOperationgetRandomInt作爲Task的靜態方法。以下是他們的新特徵:

public static Task getNewTask(int level, int count) 
public static int getOperation(int count) 
public static int getRandomInt(int from, int to) 

然後,只需刪除MathTask,並呼籲:

Task t = Task.getNewTask(level, count); 
+0

爲什麼它比OP做的更好? –

+0

@BuhakeSindi我剛剛回答'如何結合MathTask和任務來保持功能? – sp00m