这是我在Android活动中的第一次真正的Java尝试。
代码根据起始点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 :(得分: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;
}
}