本帖最后由 不二晨 于 2018-11-19 17:25 编辑
循环语句
for
格式
for( 1 初始化条件;2 循环条件;3 控制循环条件的语句){
4 循环体;
}
流程
ture
false
1 初始化条件
2 循环条件
判断
4 循环体
3 控制循环条件的语句
结束
例子
输出1~100的所有偶数,并五个偶数分一行
int count=0;
for (int i = 1; i <=100; i++) {
if(i%2==0){
System.out.print(i+" ");
count++;
if(count%5==0){
System.out.println();
}
}
}
while
格式
1 初始化条件
while( 2 循环条件 ){
3 循环体;
4 控制循环条件的语句;
}
流程
ture
false
1 初始化条件
2 循环条件
判断
3 循环体
4 控制循环条件的语句
结束
do while
格式
1 初始化条件
do {
2 循环体;
3 控制循环条件的语句;
}while( 4 循环条件 )
流程
true
false
1 初始化条件
2 循环体
3 控制循环条件的语句
4 循环条件
判断
结束
程序跳转语句
break
1.在switch中代表结束/跳出 这个switch
2.在循环中代表 结束/跳出 “当前循环”,( 一般配合if使用 )
continue
只会在循环中使用,结束本次循环,继续下次循环,( 一般配合if使用 )
return
结束/跳出 当前方法 ( 一般配合if使用 )
快捷键
重命名:F2
转义字符
换行:\r\n
练习
直角三角形1
package test;
public class Triangle_1 {
public static void main(String[] args) {
for(int i = 1;i<=5;i++){
for(int j = 1;j<=i;j++){
System.out.print("o"+" ");
}
System.out.println();
}
}
}
直角三角形2
偶数行打印o,奇数行打印z
package test;
public class Triangle_2 {
public static void main(String[] args){
for(int i =1;i<=5;i++){
for(int j =1 ;j<=i;j++){
if(i%2==0){
System.out.print("o"+" ");
}else{
System.out.print("z"+" ");
}
}
System.out.println();
}
}
}
等腰三角形1
思路:
先用循环做出左边白色部分的三角形,再做出右边部分的三角形(下面几题均适用)
package test;
public class Triangle_3 {
public static void main(String[] args) {
for(int i =5;i>0;i--){
for(int j = 0;j<i;j++){
System.out.print(" ");
}
for(int z = 5;z>=i;z--){
System.out.print("o"+" ");
}
System.out.println();
}
}
}
等腰三角形2
偶数行打印z,奇数行打印o
package test;
public class Triangle_4 {
public static void main(String[] args) {
for(int i =5;i>0;i--){
for(int j = 0;j<i;j++){
System.out.print(" ");
}
for(int z = 5;z>=i;z--){
if(i%2==0){
System.out.print("z"+" ");
}else{
System.out.print("o"+" ");
}
}
System.out.println();
}
}
}
菱形
package test;
public class Rhombus {
public static void main(String[] args) {
for(int i =5;i>0;i--){
for(int j = 1;j<i;j++){
System.out.print(" ");
}
for(int k = 5;k>=i;k--){
System.out.print("o"+" ");
}
System.out.println();
}
for(int x = 1;x<=4;x++){
for(int y = 1;y<=x;y++){
System.out.print(" ");
}
for(int z=4;z>=x;z--){
System.out.print("o"+" ");
}
System.out.println();
}
}
}
九九乘法表
package test;
public class Math {
public static void main(String[] args){
int sum = 1;
for(int i = 1;i<=9;i++){
for(int j = 1;j<=i;j++){
sum = i*j;
System.out.print(i+"x"+j +"="+sum +" ");
}
System.out.println();
}
}
}
---------------------
【转载】
作者:欧皇柯基
原文:https://blog.csdn.net/qq_42829628/article/details/83866407
|
|