循环和条件分支——从99到0的依次输出的实现

1、For循环的实现

public class From99to0For {
	public static void main(String[]args){
		
		
		for(int x=99;x>0||x==0;x=x-1 ){
			System.out.println(x);
		}
	}

}

FOR语句中的int x=99所占的位置被称为单次表达式,属于初始化部分,初始部分会进入循环体进行循环(自己理解)
2、while循环和if测试实现

public class From99to0Ifwhile {
	public static void main(String[]args){
		int x=100;
		while(x<101){
			x=x-1;
			if(x>0||x==0){
				System.out.println(x);
				}

		}
		
		
		
	}

}

虽然结果出现但是存在错误,展示结果如下
在这里插入图片描述

会出现一串莫名其妙的数字不知道为啥

3、啤酒瓶童谣实现99-0


	public static void main(String[]args){
		int beerNum=99;//定义啤酒数量
		String word="bottles";//定义String变量,使其内容是bottles,不用重复编写
		while(beerNum>0){
			if(beerNum==1){
				word="bottle";//如果剩下的啤酒只有一瓶,那么bottles就重新定义为bottle
			}
			System.out.println(beerNum+" "+word+" "+"of beer on the wall");//在剩下的酒的数量大于0的时候,表示还有多少瓶酒
			System.out.println(beerNum+" "+word+" "+"of beer.");//在剩下的酒的数量大于0的时候,啥意思不知道
			System.out.println("Take one down.");//拿下了一瓶
			System.out.println("Pass it around.");//不知道啥意思,大概就是结束一次取酒过程
			beerNum=beerNum-1;
			if(beerNum>0){
				if(beerNum==1){
					word="bottle";//如果剩下的啤酒只有一瓶,那么bottles就重新定义为bottle
				}
				
				System.out.println(beerNum+" "+word+ " "+ "of beer on the wall");
				
			}
			else{
				System.out.println("No more bottles of beer on the wall");
			}
		
	
		}
	}

}

使用while循环和if测试实现的,但是不会出现一连串的奇怪数字
4、依照啤酒歌谣改编


public class From99to0ifwhile1 {
	public static void main(String[]args){
		int x=99;
		while(x>0){
			System.out.println(x);
			x=x-1;
			if(x==0){
				System.out.println(x);
			}
		}
	}

}

输出结果正常

发布了7 篇原创文章 · 获赞 0 · 访问量 96

猜你喜欢

转载自blog.csdn.net/qq_35956737/article/details/104072458