1、用while来累加一个不超过特定值的数
原方法:
while (tempSum <= tempMax - (tempValue + 1)) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while
System.out.println(tempSum);
改进后:
while (tempSum <= tempMax) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while
tempSum -= tempValue;
System.out.println(tempSum);
(由于是实现的累加,会出现在倒数第二个数满足条件,但依旧会执行累加,即得到的sum总是会大于指定的数值。原方法是在判断条件上改变[即每次循环都会执行一次基本算数运算],而改进后的代码只用在最后进行一次基本算数运算)
2、在用String记录输出数组时:用for循环遍历数组,除最后一个数据外,需要在每个数据后面加逗号隔开。
原方法:
for (int i = 0; i < length; i++) {
if (i != length - 1) {
resultString += data[i] + ",";
} else {
resultString += data[i];
}
}
改进后:
for (int i = 0; i < length - 1; i++) {
resultString += data[i] + ",";
}
resultString += data[length - 1];
(改进后的代码不需要每次for循环就进行一次判断,进行同样次数的累加,却省去了每次的判断)
3、链表,根据给定元素找元素位置的方法。
原方法:
public int locate(int paraValue) {
int tempPosition = -1;
Node tempNode = header.next;
int tempCurrentPosition = 0;
while (tempNode != null) {
if (tempNode.data == paraValue) {
tempPosition = tempCurrentPosition;
break;
}
tempNode = tempNode.next;
tempCurrentPosition++;
}
return tempPosition;
}
改进后:
public int locate(int paraValue) {
Node tempNode = header.next;
int tempCurrentPosition = 0;
while (tempNode != null) {
if (tempNode.data == paraValue) {
return tempCurrentPosition;
}
tempNode = tempNode.next;
tempCurrentPosition++;
}
return -1;
}
在原来的基础上,while循环里判断为true时,直接return当前的位置,遍历完了没有找到,则执行最后的return -1。(tip:在自己写方法时,有时循环中的break可以用return替换。)