java中有多个while循环如何返回到已经循环过的while,Java的while循环

Java中有好几种循环语句。 while循环是Java的循环之一。

while循环用于重复执行一些语句,直到条件返回false。 如果事先不知道迭代次数,建议使用while循环。

while循环的声明如下:

while (condition) {

// 循环语句块

}

我们来看个简单的例子:

通过while循环打印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++;

}

}

}

运行程序后结果显示如下:

1 2 3 4 5

如果你仍然对while循环感到不解的话,我们通过以下流程图来理解它。

95530bd8252b

示例1

打印从1到5的奇数

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

}

}

}

程序运行结果如下:

1 3 5

练习1

如果给一整型数组,需要在该数组中找到某一元素。

输入:

{33,46,53,63,42,12}

你需要编写一程序来搜索数组中的元素。如果在数组中找到该元素,则返回“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";

}

}

程序运行结果如下:

53 is present in the array

PRESENT

无限循环

你需要小心在while循环中的循环条件,否则你可能会创建一个无限循环。

例如:

我们通过以下程序来打印10到1的数字

package org.loop;

public class InfiniteLoop {

public static void main(String[] args) {

int i = 10;

while (i > 0) {

System.out.print(" " + i);

i--;

}

}

}

程序运行结果如下:

10 9 8 7 6 5 4 3 2 1

在上面示例中,假如我们将i--;改为i++; 示例中的while循环则为无限循环。

package org.loop;

public class InfiniteLoop {

public static void main(String[] args) {

int i = 10;

while (i > 0) {

System.out.print(" " + i);

i++;

}

}

}

另外一种无限循环示例:

package org.loop;

public class InfiniteLoop {

public static void main(String[] args) {

int i = 10;

while (true) {

System.out.print(" " + i);

i++;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值