Use “continue“ and “break“ to control the loop structure and make the program better.

写一段循环语句,其中在循环中,加入continue,


class Test{
	public static void main(String args[]){
		System.out.println("Loop Starts");
		for(int i=1;i<11;i++){
			if(i==6){
				continue;
			}
			
			System.out.println(i);
		}
		System.out.println("Loop Ends");
	}
}

 continue的意思为结束本次循环,直接进入下一次的循环。

把break 换成continue ,会发现结束了本次循环,只会输出到5

Coding exercise--"break"

Find all the prime numbers within 1000 with"break"; print them out and calculate how many totally?

质数是在大于1的自然数中,只能被1和它本身整除的数字,为质数所以1和0 都不是质数。

首先,判断一个数是不是质数?

boolean isPrime=true;
            for(int i=2;i<=a-1;i++){
                if(a%i==0){
                    isPrime=false;//一旦被除尽,则用break循环结束,
                    break;}

然后在2-1000的范围内,循环数字进行挨个的取余判断,

for(int a=2;a<=1000;a++){

} 把以上代码,放到这层循环内。

两层循环嵌套完毕,则把这些质数,打印出来,再来一个条件判断,如果是质数,则打印出来,并且打印一次totalNumber+1一次,最后在循环的外面,输出totalNumber的值,就可以知道有多少个质数了。

全部的代码如下:


class Test{
	public static void main(String args[]){
		int totalNumber=0;
		for(int a=2;a<=1000;a++){
			boolean isPrime=true;
			for(int i=2;i<=a-1;i++){
				if(a%i==0){
					isPrime=false;
					break;
				}
			}
			if(isPrime==true){
				System.out.println(a);
				totalNumber++;
			}
			
		}
		System.out.println("Total prime number is: "+totalNumber);
	}
}

注意:break continue 作用的范围只包含在最内层的循环,而不能结束外层的循环。

while 循环

for循环,是在我们确定循环次数的条件下,

The while loop: when we don’t know exactly how many iterations. 

//dead loop
class Test{
    public static void main(String args[]){
        int a=1;
        while(a>1){
            System.out.println(a);
            a++;
        }
    }
}

while和if长得很像,然而if是只循环了一次,while是直到循环变为了假,才会结束循环。

A while loop and the for loop can always be converted.  这两个循环永远可以相互转换。

Task: print out the 9X9 multiplication table with both for loop and while loop.


class Test{
    public static void main(String args[]){
        int i=1;
        while(i<=10){
            System.out.println(i);
            i++;
        }//替换写法
        for(int j=1;j<=10;j++){
            System.out.println(j);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值