2013-04-22 98 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