写一段循环语句,其中在循环中,加入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);
}
}
}