Java中有好幾種循環(huán)語句。 while循環(huán)是Java的循環(huán)之一。
while循環(huán)用于重復(fù)執(zhí)行一些語句冯吓,直到條件返回false。 如果事先不知道迭代次數(shù)萍倡,建議使用while循環(huán)胖喳。
while循環(huán)的聲明如下:
while (condition) {
// 循環(huán)語句塊
}
我們來看個簡單的例子:
通過while循環(huán)打印1到5
package org.loop;
public class WhileLoop {
public static void main(String[] args) {
int i = 1;
while (i < 6) {
System.out.print(" " + i);
i++;
}
}
}
運(yùn)行程序后結(jié)果顯示如下:
1 2 3 4 5
如果你仍然對while循環(huán)感到不解的話,我們通過以下流程圖來理解它叠必。
示例1
打印從1到5的奇數(shù)
package org.loop;
public class OddOnly {
public static void main(String[] args) {
int i = 1;
while (i < 6) {
if (i % 2 == 1)
System.out.print(" " + i);
i++;
}
}
}
程序運(yùn)行結(jié)果如下:
1 3 5
練習(xí)1
如果給一整型數(shù)組,需要在該數(shù)組中找到某一元素妹窖。
輸入:
{33,46,53,63,42,12}
你需要編寫一程序來搜索數(shù)組中的元素纬朝。如果在數(shù)組中找到該元素,則返回“PRESENT”骄呼,否則返回“NOT PRESENT”
package org.loop;
public class WhileFindOne {
public static void main(String[] args) {
WhileFindOne bse = new WhileFindOne();
int arr[] = { 33, 46, 53, 63, 42, 12 };
System.out.println(bse.findElementInArr(arr, 53));
}
public String findElementInArr(int arr[], int elementTobeFound) {
int i = 0;
while (i < arr.length) {
if (arr[i] == elementTobeFound) {
System.out.println(elementTobeFound + " is present in the array ");
return "PRESENT";
}
i++;
}
return "NOT PRESENT";
}
}
程序運(yùn)行結(jié)果如下:
53 is present in the array
PRESENT
無限循環(huán)
你需要小心在while循環(huán)中的循環(huán)條件共苛,否則你可能會創(chuàng)建一個無限循環(huán)判没。
例如:
我們通過以下程序來打印10到1的數(shù)字
package org.loop;
public class InfiniteLoop {
public static void main(String[] args) {
int i = 10;
while (i > 0) {
System.out.print(" " + i);
i--;
}
}
}
程序運(yùn)行結(jié)果如下:
10 9 8 7 6 5 4 3 2 1
在上面示例中,假如我們將i--;改為i++; 示例中的while循環(huán)則為無限循環(huán)隅茎。
package org.loop;
public class InfiniteLoop {
public static void main(String[] args) {
int i = 10;
while (i > 0) {
System.out.print(" " + i);
i++;
}
}
}
另外一種無限循環(huán)示例:
package org.loop;
public class InfiniteLoop {
public static void main(String[] args) {
int i = 10;
while (true) {
System.out.print(" " + i);
i++;
}
}
}