语句嵌套(for中for)、break(跳出)\continue(继续)

/*
语句嵌套:就是语句中还有语句。
现在要学的是 循环嵌套。
*/
class ForForDemo
{
public static void main(String[] args)
{
for (int x= 0;x<3;x++)
{
for (int y=0;y<4;y++) //共打印12次ok。
{
System.out.println(“Ok”);
}
}
}
}

打印星星
1****
2****
3****
4****

class ForForDemo
{
public static void main(String[] args)
{
for (int x= 0;x<3;x++) //外循环:控制行数
{
for(int y =0;y<4;y++) //内循环,控制列数,也就是每一行的个数。
{
System.out.print("");
}
System.out.println(); //只有一个功能,就是换行。
}
}
}
1*****
2
***
3***
4**
5*
class ForForDemo
{
public static void main(String[] args)
{
int z = 5; int z=0;
for (int x =0;x<=5;x++) //x<5 :因为外循环控制行数,一共5行。
{
for (int y =0;y {
System.out.print("**");
}
System.out.println();
z–; z++;
}
}
}
/
class ForForDemo
{
public static void main(String[] args)
{
int z =0;
for (int x = 0;x<=5;x++)
{
for(int y = z;y<=5;y++) //这种更加舒服一些
{
System.out.print("*");
}
System.out.println();
z++;
}

}

}

打印星星
1*
2**
3***
4****
5*****
class ForForDemo
{
public static void main(String[] args)
{
for(int x = 0;x<=5;x++) //x<=5;因为外循环有5行。
{
for (int y=0 ;y {
System.out.print("*");
}
System.out.println();
}
}
}

总结:三角形尖朝上时改变初始化值
三角形尖朝下时改变条件

需求:
1
12
123
1234
12345

class ForForDemo
{
public static void main(String[] args)
{
for (int x=1;x<=5;x++)
{
for(int y=1;y<=x;y++)
System.out.print(y);
System.out.println();
}
}
}

需求:打印九九乘法表
class ForForDemo
{
public static void main(String[] args)
{
for(int x=1;x<=9;x++)
{
for(int y=1;y<=x;y++)
{
System.out.print(y+""+x+"="+yx+"\t"); "\t "为制表符
}
System.out.println();
}
}
}

break语句:应用于选择结构和循环结构 (switch和循环结构)
break:只能跳出当前循环
continue语句:只能应用于循环结构,继续循环。
特点:结束本次循环,进入下次循环
例子:
class ForForDemo
{
public static void main(String[] args)
{
w:for(int x=0;x<3;x++) // w: 为标号,只能用于循环结构,给循环起名字
{
q:for(int y = 0;y<4:y++)
{
System.out.println(“x=”+x);
break w; //直接跳出外循环
}
}
}
}

1.break和continue的作用范围
2.break和continue单独存在时,下面不能有任何语句,因为执行不到。
class ForForDemo
{
public static void main(String[] args)
{
for (int x=1;x<10;x++)
{
if(x%2==1)
continue;
System.out.println(“x=”+x);
}
}
}

class ForForDemo
{
public static void main(String[] args)
{
for (int x=0;x<5;x++)
{
for(int y = x+1;y<5;y++)
{
System.out.print("-");
}
for(int z=0;z<=x;z++)
{
System.out.print("*");
}
System.out.println();
}
}
}

你可能感兴趣的:(java)