1.13.3 循环控制
循环嵌套:一个循环定义在另一个循环里面
循环控制:continue:跳过本次循环剩下的代码,跳到所在循环的第三部分(x++)
break:跳出所在循环,跳到所在循环结束的部分
循环标签:当多个循环嵌套在一起的时候,如果代码写在内层,控制外层循环时,需要给外层循环贴标签(a:)
然后在内层循环里continue/break+标签名;
例子:用for循环嵌套输出对应数字/图形
public class DrawPicLoop{
public static void main(String[] args){
/**矩形
********
********
********
********
*/
for (int i=1 ;i<=4;i++){
for(int j=1 ;j<=8;j++){
System.out.print("*");
}
System.out.println();
}
//乘法表
for (int i=1 ;i<=9;i++){
for(int j=1 ;j<=i;j++){
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}
//三角形
for (int i=1 ;i<=3;i++){
for(int j=1 ;j<=8-i;j++){
System.out.print(" ");
}
for(int j =1;j<=2*i-1;j++){
System.out.print("*");
}
System.out.println();
}
/**裤衩
***** *****
***** *****
***** *****
*/
for (int i=1 ;i<=3;i++){
for(int j=1 ;j<=3-i;j++){
System.out.print(" ");
}
for(int j=1;j<=5;j++){
System.out.print("*");
}
for(int j =1;j<=2*i-1;j++){
System.out.print(" ");
}
System.out.println("*****");
}
}
}
求1-100之间的质数:
方法一:
public class Sushu2{
public static void main(String[] args){
//最小的素数是2
//2 3 5 7 11 13 17 19.....
//循环嵌套+循环控制+循环标签
for(int i =2;i<=100;i++){
int count=0;
for(int num=2;num<i;num++){
if( i%num==0){
count++;
}
}
if(count==0){
System.out.print("质数有"+i);
}}}}
方法二:
public class Sushu3{
public static void main(String[] args){
//最小的素数是2
//2 3 5 7 11 13 17 19.....
//循环嵌套+循环控制+循环标签
System.out.print("质数有"+2+" ");
a:for(int i =3;i<=100;i+=2){
for(int num=3;num<Math.sqrt(i);num+=2){
if( i%num==0){
continue a;
}
}
System.out.print(i+" ");
}}}
用for循环嵌套提亮图片颜色
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class PS{
public static void main(String[] args)throws Exception{
int c=13;
File f = new File("splash.jpg");
BufferedImage image = ImageIO.read(f);
for(int x=0;x<image.getWidth();x++){
for(int y=0;y<image.getHeight();y++){
int color=image.getRGB(x,y);
int red = color>>16&255;
int green =color>>8&255;
int blue= color&255;
red=red*c/10;
red =red>255?255:red;
green=green*c/10;
green =green>255?255:green;
blue = blue*c/10;
blue = blue>255?255:blue;
int newcolor = red<<16| green<<8 |blue;
image.setRGB(x,y,newcolor);
}
}
ImageIO.write(image,"jpg",new File("splash2.jpg"));
}}
图片前后比对: