while和do—while循环语句
程序员文章站
2023-12-25 23:24:15
...
while循环语句
格式:
while(判断条件语句){
循环体语句;
}
扩展格式:
初始化语句;
while(判断条件语句){
循环体语句;
控制条件语句;
}
实例一
猜字游戏
思路:
While循环:
- 猜的数字:int num = 456;
- 条件:int guess;
- while(guess != num){
- 猜数字;
- guess < num;猜小了
- guess > num;猜大了
- guess == num;break;
- }
- 猜对了!
public class WhileDemo {
public static void main(String[] args) {
//int num = 456;
//随机产生 Math.random()------0.0-0.9999999...
int num = (int)(Math.random()*1000) + 1;
//System.out.println("要猜的数字是" + num);
Scanner sc = new Scanner(System.in);
System.out.println("请输入猜的数字:");
int guess = sc.nextInt();
while(guess != num){
if(guess > num){
System.out.println("猜大了");
}else{
System.out.println("猜小了");
}
System.out.println("继续猜!");
guess = sc.nextInt();
}
if(guess == num){
System.out.println("恭喜你,猜对了");
}
sc.close();
}
}
do-while循环语句
格式:
do{
循环体语句;
}while(判断条件语句);
实例一
猜字游戏
public class DoWhileDemo {
public static void main(String[] args) {
int num = (int)(Math.random()*1000) + 1;
Scanner sc = new Scanner(System.in);
System.out.println("请输入要猜的数字");
int guess = sc.nextInt();
do{
if(guess > num){
System.out.println("猜大了");
}else{
System.out.println("猜小了");
}
System.out.println("继续猜!");
guess = sc.nextInt();
}while(guess != num);
if(guess == num){
System.out.println("猜对了");
}
}
}
break和continue的区别:
continue:使用循环结构中,用于结束本次循环继续下一次循环。
break:可以使用在switch结构和循环结构中,用于跳出当前结构。
案例
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if(i % 2 == 0){
continue;
}
System.out.print(i);
}
}
}
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if(i == 2){
break;
}
System.out.print(i);
}
}
}