gpt4 book ai didi

java - 使用 for 循环的更好方法?

转载 作者:行者123 更新时间:2023-12-01 14:39:24 24 4
gpt4 key购买 nike

这是我第一次真正的 Java 尝试,在 Android Activity 中。

代码基于起点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);

最佳答案

作为基本经验法则,您计算的任何内容都将其保存到变量中。这使事情看起来更简单,并防止计算多次运行。

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;
}
}

关于java - 使用 for 循环的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com