1、应用场景
for循环更偏重于从头到尾的范围的便利,如遍历一个数组。
while循环,更偏重于满足于某个条件下的数据的处理。
2、二者又是可以完全互换的
for转while
int [] arrray={1,2,3};
int i=0;
// for (i = 0; i < arrray.length-1; i++) {
//处理数据
//}
//for 转while
while(i<arrray.length-1){
i++;
//处理数据
}
while转for
拿二分查找的代码为例
public int search(int[] nums, int target) {
//边界判断
int left=0;
int right=nums.length-1;
// while (left<=right) {
// int index=(right +left)/2;
// int current = nums[index];
// if (current > target) { //左移
// right=index-1;
// } else if (current < target) {//右移
// left=index+1;
// } else {//返回下标
// return index;
// }
// }
//while转for
for (;left<=right;) {
int index=(right +left)/2;
int current = nums[index];
if (current > target) { //左移
right=index-1;
} else if (current < target) {//右移
left=index+1;
} else {//返回下标
return index;
}
}
return -1;
}