2013-04-22 105 views
0

這是我第一次真正的Java嘗試,在android活動中。更好的方式來使用循環?

代碼根據起始點countStart和結束點count1進行計數。我沒有包括整個班級,但在toString之後,它創建了一個textview並顯示了從該數組生成的字符串(顯然我猜...)

它根據多少個插槽需要,我不想讓數組太大,因爲最後輸出零。

有人能告訴我如何使此代碼更有效率? (較少的線路,減少混亂,更快,更少的內存使用)

//get the message from the intent 
    Intent intent = getIntent(); 
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
    //convert string to double 
    double count1 = Double.parseDouble(message); 
    //declare variables and arrays 
    double[] countArray; 
    double countStart = 3.5; 
    //initialize array with exact number of elements needed 
    countArray = new double[((int) (count1-countStart)) +1]; 

    //counts from countStart to count1 without going over count1 
    for(double i=0; i<(((int) count1-countStart) + 1); i++) { 
     if ((countStart+i)>count1) { 
      break; 
     } else { 
      countArray[((int) i)] = countStart+i; 
     } 

    } 

    //convert array to string 
    String mensage = Arrays.toString(countArray); 
+0

代碼複習問題屬於http://codereview.stackexchange.com。 – 2013-04-22 00:55:38

回答

1

根據經驗的基本規則,任何你計算的東西保存到一個變量。這使事情看起來更簡單,並防止計算多次運行。

double count1 = Double.parseDouble(message); 
double countStart = 3.5; 

int resultCount = (int)(count1 - countStart) + 1; 
double results = new double[resultCount]; 

for(double i = 0; i < resultCount; ++i) { 
    double result = countStart + i; 
    if (result > count1) { 
     break; 
    } else { 
     results[i] = result; 
    } 
} 
+0

謝謝,這是有道理的,而且是更清潔! – 2013-04-22 01:19:38