由浅到深认识Java语言(6):控制流程语句

该文章Github地址:https://github.com/AntonyCheng/java-notes【有条件的情况下推荐直接访问GitHub以获取最新的代码更新】

在此介绍一下作者开源的SpringBoot项目初始化模板(Github仓库地址:https://github.com/AntonyCheng/spring-boot-init-template【有条件的情况下推荐直接访问GitHub以获取最新的代码更新】& CSDN文章地址:https://blog.csdn.net/AntonyCheng/article/details/136555245),该模板集成了最常见的开发组件,同时基于修改配置文件实现组件的装载,除了这些,模板中还有非常丰富的整合示例,同时单体架构也非常适合SpringBoot框架入门,如果觉得有意义或者有帮助,欢迎Star & Issues & PR!

上一章:由浅到深认识Java语言(5):运算符

13.流程控制语句

流程控制语句 { 顺序结构 分支结构 循环结构 \bf{流程控制语句}\begin{cases} \bf{顺序结构}\\\bf{分支结构}\\\bf{循环结构} \end{cases} 流程控制语句 顺序结构分支结构循环结构

很多流程里都是循环里包含着分支,分支和循环都是以顺序结构为基础;

顺序结构

程序最基本的执行结构就是顺序结构,即程序是顺序执行的,从上到下;

分支结构

import java.util.Scanner;
class demo{
    public static void main(String[] args){
        System.out.println("请输入一个年龄:");
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        if(age<18){
            System.out.println("未成年!");
        }else if(age<30){
            System.out.println("已成年!");
        }else if(age<45){
            System.out.println("已壮年!");
        }else{
            System.out.println("已老年!");
        }
    }
}

程序提供了多条分支,但在执行时,根据实际情况只会选择其中一条分支来执行;

if-else

语法结构:

if(条件一){
	执行语句一;
}else if(条件二){
	执行语句二;
}else if(条件三){
	执行语句三;
}else{
	执行语句四;
}

示例如下:

class demo{
    public static void main(String[] args){
        int a = 10;
        int b = 20;
        if(a>b){
            System.out.println("a>b");
        }
        else if(a<b){
            System.out.println("a<b");
        }
        else {
            System.out.println("a=b");
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

注意:

  1. if(条件) 之后的内容,可以是一条语句,也可以是多条语句组成的语句块,语句块就必须用 {} 包裹,如果没有使用 {} 包裹,那么就只能有一条语句,作为 if(语句) 之后的内容;

    package top.sharehome.Bag;
    
    public class Demo {
    	public static void main(String[] args) {
    		int a = 3, b = 4;
    		if(a>b)
    			System.out.println("a.hello world");
    			System.out.println("b.hello world");
    	}
    }
    

    打印效果如下:

    外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

    上例说明,第二条 hello world 没有被包含在 if 语句之内,所以被打印了出来;

  2. 条件一定是 boolean 表示;

案例一:

只有年龄超过18岁的学生才能玩游戏,现在编写一个程序,来判断一个学生是否可以玩游戏;

示例如下:

import java.util.Scanner;
class demo{
    public static void main(String[] args){
        System.out.println("请输入你的年龄:");
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        if(age<18){
            System.out.println("不可以玩游戏");
        }else{
            System.out.println("可以玩游戏");
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例二:

如果成绩大于 90 ,男生的话送一台 Xbox,女生的话送一只口红;

示例如下:

import java.util.Scanner;
class demo{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的成绩:");
        double score = sc.nextDouble();
        System.out.println("请输入你的性别(男/女==1/2):");
        int sex = sc.nextInt();
        if (score<90){
            System.out.println("没有礼物!");
        }else{
            if(sex == 1){
                System.out.println("送你Xbox!");
            }else if(sex == 2){
                System.out.println("送你口红!");
            }
            else{
                System.out.println("请输入切确性别!");
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例三:

妻子嘱咐丈夫回家是买十个苹果,如果碰到卖西瓜的买一个,变成模拟场景;

示例如下:

import java.util.Scanner;
class demo{
    public static void main(String[] args){
        System.out.println("首先,你想有卖西瓜的人么?有/无 == 1/0");
        Scanner sc = new Scanner(System.in);
        int sellWM = sc.nextInt();
        System.out.println("丈夫回家了,但水果店还开着,需要去买苹果!");
        System.out.println("...");
        System.out.println("挑苹果……");
        System.out.println("挑了 10 个苹果!");
        if (sellWM == 1){
            System.out.println("有西瓜,买一个吧!");
            System.out.println("和自己媳妇儿一起吃西瓜!");
        }else{
            System.out.println("没西瓜,算了!");
            System.out.println("给自己媳妇说没有西瓜,然后上床睡觉去了!");
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例四:

从键盘输入一个成绩,根据成绩的情况给出等级,要求顺序书写和嵌套书写;

顺序写法:

import java.util.*;
class demo{
    public static void main(String[] args){
        System.out.println("请输入你的成绩:");
        Scanner sc = new Scanner(System.in);
        double score = sc.nextDouble();
        if(score < 60){
            System.out.println("不及格!");
        }
        else if(score < 70){
            System.out.println("中下等!");
        }
        else if(score < 80){
            System.out.println("中上等!");
        }
        else if(score < 90){
            System.out.println("良等!");
        }
        else if(score < 100){
            System.out.println("优等!");
        }
        else{
            System.out.println("最佳!");
        }
    }
}

嵌套写法:

import java.util.*;
class demo{
    public static void main(String[] args){
        System.out.println("请输入你的成绩(0-100):");
        Scanner sc = new Scanner(System.in);
        double score = sc.nextDouble();
        if (score < 60){
            System.out.println("不及格!");
        }
        else{
            if(score <70){
                System.out.println("中下等!");
            }
            else{
                if(score <80){
                    System.out.println("中上等!");
                }
                else{
                    if(score <90){
                        System.out.println("良等!");
                    }
                    else{
                        if(score <100){
                            System.out.println("优等!");
                        }
                        else{
                            System.out.println("最佳!");
                        }
                    }
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例五:

年龄程序,让用户输入年龄,告诉用户结论;

示例如下:

import java.util.*;
class demo{
    public static void main(String[] args){
        System.out.println("请输入你的年龄:");
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        if(age<0){
            System.out.println("输入错误!");
        }else if(age<18){
            System.out.println("你未成年!");
        }else if(age<25){
            System.out.println("年龄轻轻!");
        }else if(age<35){
            System.out.println("青壮年!");
        }else if(age<45){
            System.out.println("正值壮年!");
        }else if(age<55){
            System.out.println("正值中年!");
        }else if(age<65){
            System.out.println("将步入老年!");
        }else if(age<100){
            System.out.println("已经老年!");
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例六:

完成如下打印;

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

示例如下:

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入T恤价格:");
        double TPrice = sc.nextDouble();
        System.out.println("请输入网球鞋价格:");
        double TennisShoePrice = sc.nextDouble();
        System.out.println("请输入网球拍价格:");
        double TennisPrice = sc.nextDouble();
        System.out.println("请输入购买T恤购买数量:");
        int TQuantity = sc.nextInt();
        System.out.println("请输入购买网球鞋的数量:");
        int TennisShoeQuantity = sc.nextInt();
        System.out.println("请输入购买网球拍的数量:");
        int TennisQuantity = sc.nextInt();
        double all = TennisPrice + TPrice + TennisShoePrice;
        double Discount = 0;
        if(all<1000){
            Discount = 10;
        }else if(all<2000){
            Discount = 8;
        }else if(all<3000){
            Discount = 7.5;
        }else if(all<4000){
            Discount = 6;
        }else{
            Discount = 5;
        }
        System.out.println("***************消费单***************");
        System.out.println("购买物品\t单价\t个数\t金额");
        System.out.println("T恤\t\t"+TPrice+"\t"+TQuantity+"\t"+TPrice*TQuantity);
        System.out.println("网球鞋\t\t"+TennisShoePrice+"\t"+TennisShoeQuantity+"\t"+TennisShoePrice*TennisShoeQuantity);
        System.out.println("网球拍\t\t"+TennisPrice+"\t"+TennisQuantity+"\t"+TennisPrice*TennisQuantity);
        System.out.println("***********************************");
        System.out.println("折扣:\t"+Discount+"折");
        System.out.println("消费总额:\t"+"¥"+(TPrice*TQuantity+TennisPrice*TennisQuantity+TennisShoePrice*TennisShoeQuantity));
        System.out.println("实际消费:\t"+"¥"+((TPrice*TQuantity+TennisPrice*TennisQuantity+TennisShoePrice*TennisShoeQuantity)*(Discount*0.1)));
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

注意:\t 是制表符,即 Tab ;

switch-case

语法结构:

swich(表达式){
	case 条件一 :
        语句一;
        break;
    case 条件二 :
        语句二;
        break;
    default :
        语句三;
        break;
}
注意:break 是为了防止 case 穿透;
     表达式是一个能够产生值的语句,可能是变量,也可以是语句;
     如果表达式都不满足以下条件,则运行 default 语句;

注意:

表达式的种类:byte , short , char , int , 枚举 , String

case 后跟的必须是一个固定的值,不能是范围;

case 穿透指的是

案例一:

输入一个月份,判断当前月份是属于哪一个季节,只能用 swich 来做;

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入当前月份:");
        int month = sc.nextInt();
        switch (month){
            case 2:
            case 3:
            case 4:
            System.out.println("春天");
            break;
            case 5:
            case 6:
            case 7:
            System.out.println("夏季");
            break;
            case 8:
            case 9:
            case 10:
            System.out.println("秋季");
            break;
            case 11:
            case 12:
            case 1:
            System.out.println("冬季");
            break;
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例二:

使用 swich 语句改写判断学生成绩的等级;

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("写出学生的成绩(0-100):");
        double score = scanner.nextDouble();
        int result = (int)score/10;
        switch(result){
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            System.out.println("不及格");
            break;
            case 6:
            case 7:
            System.out.println("中");
            break;
            case 8:
            System.out.println("良");
            break;
            case 9:
            case 10:
            System.out.println("优");
            break;
            default:
            System.out.println("请重新输入!");
            break;
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例三:

利用 switch 实现一个计算机操作:第一次输入一个整数,第二次输入一个运算符,第三次输入一个整数;

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个整数:");
        double a = scanner.nextDouble();
        System.out.println("请输入运算符:");
        String c = scanner.next();
        System.out.println("请输入第二个整数:");
        double b = scanner.nextDouble();
        double result = 0;
        switch(c){
            case "+":
            result = a+b;
            System.out.println(result);
            break;
            case "-":
            result = a-b;
            System.out.println(result);
            break;
            case "*":
            result = a*b;
            System.out.println(result);
            break;
            case "/":
            result = a/b;
            System.out.println(result);
            break;
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

程序实例

示例一:

定义三个整型变量 x , y , z ,并且从键盘初始化变量值,判断三个变量的大小,将较大的值赋给变量 max ,将 max 输出,注意输入使用 scanner 输入;

import java.util.*;
class demo{
    public static void main(String[] args){
        int a;
        int b;
        int c;
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个数:");
        a = sc.nextInt();
        System.out.println("请输入第二个数:");
        b = sc.nextInt();
        System.out.println("请输入第三个数:");
        c = sc.nextInt();
        int max = 0;
        if(a>=b&&a>=c){
            max = a;
        }else if(b>=a&&b>=c){
            max = b;
        }else if(c>=a&&c>=b){
            max = c;
        }
        System.out.println("最大值:"+max);
    }
}

也可以用三元运算符获得这样的结论:

import java.util.*;
class demo{
    public static void main(String[] args){
        int a;
        int b;
        int c;
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个数:");
        a = sc.nextInt();
        System.out.println("请输入第二个数:");
        b = sc.nextInt();
        System.out.println("请输入第三个数:");
        c = sc.nextInt();
        int max = 0;
        max = a > c ? a > b ? a : b : c > b ? c : b;
        // a>c? (a>b?a:b) : (c>b?c:b);
        System.out.println("最大值:" + max);
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例二:

饭店里面有五道菜:黄花鱼200块;烤鸭100块;红烧肉60块;小炒肉40块;白水豆腐10块;一个客人进了饭店,根据身上的钱来决定吃哪一道菜,编程模拟:

import java.util.*;
class demo{
    public static void main(String[] args){
        int a = 10;
        int b = 40;
        int c = 60;
        int d = 100;
        int e = 200;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你现在有的钱:");
        int MY_MONEY = scanner.nextInt();
        if(MY_MONEY>=200){
            System.out.println("上黄花鱼!");
            MY_MONEY -= 200;
        }else if(MY_MONEY>=100){
            System.out.println("上烤鸭!");
            MY_MONEY -= 100;
        }else if(MY_MONEY>=60){
            System.out.println("上红烧肉!");
            MY_MONEY -= 60;
        }else if(MY_MONEY>=40){
            System.out.println("上小炒肉!");
            MY_MONEY -= 40;
        }else if(MY_MONEY>=10){
            System.out.println("上白水豆腐!");
            MY_MONEY -= 10;
        }else{
            System.out.println("你没钱!");
        }
        System.out.println("你还有"+MY_MONEY+"块钱!");
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例三:

编写程序,判断给定的某个年份是否为闰年(闰年能被4整除,不能被100整除,但能被400整除)

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个年份:");
        int Year = scanner.nextInt();
        if((Year%4==0 && Year%100!=0) || (Year%400==0)){
            System.out.println(Year+"是一个闰年!");
        }else{
            System.out.println(Year+"不是一个闰年!");
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例四:

编程实现已知某人的工资(要求输入),求他应该缴纳的个人所得税以及最后得到的工资。个人所得税计算方法计算方法:

全月应纳税所得额=工资薪金所得-3500

应纳税额=应纳税所得额*税率-速算扣除数

级数全月应交税所得额(x)税率(%)速算扣除数
1x<=50050
2500<x<=20001025
32000<x<=500015125
45000<x<=2000020375
520000<x<=40000251375
640000<x<=60000303375
760000<x<=80000356375
880000<x<=1000004010375
9x>1000004515375
import java.util.*;

public class demo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入你的月薪:");
		double salary = sc.nextDouble();
		double should = salary - 3500;
		if(should<=500) {
			System.out.println("你应该交 "+(should*0.05)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.05)+3500)+"块钱!");
		}else if(should>500&&should<=2000) {
			System.out.println("你应该交 "+(should*0.1-25)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.1-25)+3500)+"块钱!");
		}else if(should>2000&&should<=5000) {
			System.out.println("你应该交 "+(should*0.15-125)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.15-125)+3500)+"块钱!");
		}else if(should>5000&&should<=20000) {
			System.out.println("你应该交 "+(should*0.2-375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.2-375)+3500)+"块钱!");
		}else if(should>20000&&should<=40000) {
			System.out.println("你应该交 "+(should*0.25-1375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.25-1375)+3500)+"块钱!");
		}else if(should>40000&&should<=60000) {
			System.out.println("你应该交 "+(should*0.30-3375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.30-3375)+3500)+"块钱!");
		}else if(should>60000&&should<=80000) {
			System.out.println("你应该交 "+(should*0.35-6375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.35-6375)+3500)+"块钱!");
		}else if(should>80000&&should<=100000) {
			System.out.println("你应该交 "+(should*0.40-10375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.40-10375)+3500)+"块钱!");
		}else {
			System.out.println("你应该交 "+(should*0.45-15375)+"块钱!");
			System.out.println("你能够得到 "+(should-(should*0.45-15375)+3500)+"块钱!");
		}
		sc.close();
	}
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例五:

模拟用户登录,提示用户输入用户名和密码,和本地的数据进行比对,如果成功提示登陆成功,否则提示失败,然后循环用户是否再次输入;

import java.util.*;

public class demo {
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
		String username = "陈如颖";
        String password = "020114";
        boolean b = false;
        while(true) {
            System.out.println("请输入用户名:");
            String user = scanner.next();
            System.out.println("请输入密码:");
            String passwd = scanner.next();
            if(username.equals(user)&&password.equals(passwd)){
                System.out.println("登陆成功!");
                break;
            }else{
                System.out.println("请选择是否继续登录?(true/false)");
                b = scanner.nextBoolean();
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

循环结构

定义:满足一定的条件下,可以重复执行的语句;

java 中的循环语句:

  1. for 循环
  2. while 循环
  3. do...while 循环

循环语句的组成成分:任何一个循环语句都由四个部分组成;

举例说明:

for (int i = 0;i < 4;i++){
    System.out.println("Hello World!");
}
  1. 循环条件:能够让循环终止的条件,如果循环条件设计得不好,就很容易造成死循环;
  2. 循环变量:变量中存的数据,该数据会发生变化,当数据达到一定条件时触发终止条件;
  3. 迭代部分:让循环变量进行更新迭代,如果没有迭代部分,循环变量永远不会变化,也就不会让循环条件终止;
  4. 循环体:每次循环要做的事情;

for循环

语法结构:

for (循环变量;循环条件;迭代部分){
	循环体;
}

注意:

  1. 循环变量的定义位置:可以在 for 循环小括号之内,也可以在 for 循环外部,尽量写在小括号之内,因为该变量只存在于此循环之内;
  2. 循环条件在每次循环之前都要判断一次,当循环条件为 true 时,循环体才会被执行,否则循环结束;
  3. 迭代部分:对循环变量的更新并不是固定的 i++ ,也可以是 i += 2

案例一:

打印 0-100 之间的所有数;

import java.util.*;

class demo {
	public static void main(String[] args) {
		int i = 0;
		int count = 0;
		for (i = 0; i <= 100; i++) {
			System.out.print(i + "\t");
			count++;
			if(count == 8) {
				System.out.println();
				count = 0;
			}
		}
	}
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例二:

计算 0-100 的和;

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        int sum = 0;
        for (i = 0;i <= 100;i++){
            sum += i;
        }
        System.out.println(sum);
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例三:

打印 0-100 之间的偶数;

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        for (i = 0;i <= 100;i+=2){
            System.out.println(i);
        }
    }
}

或者 :

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        for (i = 0;i <= 100;i++){
            if (i%2==0){
                System.out.println(i);
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例四:

打印完数;

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入你想求完数的范围:0~");
        int num = scanner.nextInt();
        System.out.println("该范围里的完数有:");
        for(int i=1; i<=num; i++){
            int sum = 0;
            for(int j=1; j<i; j++){
                if(i%j==0){
                    sum += j;
                }
            }
            if(sum == i){
                System.out.print(i+"");
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

while循环

语法结构:

循环变量
while(循环变量){
	循环体;
}

案例一:

打印 0-100 之间所有的奇数;

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        while(i<=100){
            if(i%2!=0){
                System.out.println(i);
            }
            i++;
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

do…while循环

语法格式:

do{
	循环体;
	迭代部分;
}while(循环条件);

特点:无论循环条件是否成立,do...while 循环都会先执行一遍,在进行循环条件的判断!

嵌套循环

定义:一个循环充当另一个循环的循环体,也就是说循环里还有循环;(多重循环)

**关键:**内层循环条件往往和外层循环的循环变量有着紧密关系;

练习一:

打印五行 0-10 ;

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=0; i<5 ;i++){
            for (int j=0; j<11;j++){
                System.out.print(j+"\t");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习二:

打印如下图形:

*****
*****
*****
*****
*****

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=0; i<5 ;i++){
            for (int j=0; j<5;j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习三:

打印如下图形:

**
***
****
*****

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=0; i<5 ;i++){
            for (int j=0; j<=i;j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习四:

打印如下图形:

*****
****
***
**
*

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=0; i<5 ;i++){
            for (int j=0; j<5-i;j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习五:

打印如下图形:

**
***
****
*****
****
***
**
*

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=0; i<9 ;i++){
            if(i<5){
                for(int j=0; j<i+1;j++){
                    System.out.print("*");
                }
                System.out.println();
            }else{
                for(int j=0; j<9-i;j++){
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习六:

打印如下图形:

​ *
​ ***
*****
*******

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i = 0; i < 4;i++){
            for (int k = 0; k < 4-i;k++){
                //打印空格
                System.out.print(" ");
            }
            for(int j = 0; j < 2*i+1; j++){
                //打印 *
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习七:

打印如下图形:

*******
*****
***
*

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i = 0; i < 5;i++){
            for (int j = 0; j < i;j++){
                System.out.print(" ");
            }
            for (int k = 0; k < 2*(3-i)+1; k++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

练习八:

打印如下图形:

​ *
​ * *
* * *
* * * *

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i = 0; i < 4;i++){
            for (int j = 0; j < 3-i;j++){
                System.out.print(" ");
            }
            for (int k = 0; k < i+1;k++){
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

程序实例

实例一:

在控制台输出 100-999 之间所有的“水仙花数”;

所谓的水仙花数是指一个三位数,其各个位数字的立方和等于该数本身;

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        for(i = 100;i<1000;i++){
            int a = i%10;
            int b = (i/10)%10;
            int c = i/100;
            if(a*a*a+b*b*b+c*c*c == i){
                System.out.println(i+"是水仙花数!");
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例二:

一张纸的厚度是 0.2 mm,多少张纸叠加可以达到珠穆朗玛峰的高度(8848.13m);

import java.util.*;

class demo {
	public static void main(String[] args) {
		int pepar = 2;
		int count = 0;
        int mountain = 88484300;
        int i = 0;
        for(i = 0; pepar < mountain; i++){
            pepar += 2;
            count += 1;
        }
        System.out.println(count);
	}
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例三:

计算一个整数的阶层;

import java.util.*;
class demo{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num = scanner.nextInt();
        int a = 1;
        for (int i = 1; i <= num; i++){
            a *= i;
        }
        System.out.println(a);
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例四:

打印 100 以内能被 4 整除但不能被 7 整除的数据,每行打印 6 个;

import java.util.*;
class demo{
    public static void main(String[] args){
        int count = 0;
        for (int i = 0; i <= 100; i++) {
            if (i%4==0&&i%7!=0){
                System.out.print(i+"\t");
                count++;
                if (count == 6){
                    System.out.println("\n");
                    count = 0;
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例五:

打印1000以内的所有素数,每20个一行;

import java.util.*;
class demo{
    public static void main(String[] args){
        int count = 0;
        for (int i = 1; i < 1000; i++){
            boolean b = false;
            for (int j = 2; j < i; j++){
                if(i%j==0){
                    b = true;
                }
            }
            if(!b){
                System.out.print(i+" ");
                count++;
                if(count==20){
                    System.out.println();
                    count = 0;
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例六:

求 1-3+5-7+……-99+101 的值;

import java.util.*;

public class demo {
	public static void main(String[] args) {
        boolean b = true;
        int n = 0;
        for(int i = 1; i < 102; i+=2) {
            if(b==true) {
                n+=i;
                b=false;
            }else if(b==false) {
                n-=i;
                b=true;
            }
        }
        System.out.println(n);
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实例七:

百钱买百鸡:公鸡五元一只,母鸡三元一只,小鸡一元三只,如果用100元钱,不欠不赊,可以买公鸡,母鸡,小鸡各多少只?

import java.util.*;

public class demo {
	public static void main(String[] args) {
        for (int i = 0; i <21;i++ ){
            for(int j = 0; j < 34;j++ ){
                int k = 100-i-j;
                if(i*5+j*3+k*(1/3f)==100){
                    System.out.println("公鸡"+i+" 母鸡"+j+" 小鸡"+k);
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

循环总结

Q : Q: Q循环语句能帮助我们解决说明问题?

A : A: A解决要重复写的代码(循环体),循环是一定要有终止的(循环条件,循环变量迭代);

补充:死循环;

while(true){}for( ; ; ){}

任务一:

求 1-1000 之间满足“用 3 除余 2 ;用 5 除余 3 ;用 7 除余 2 ”的数,且一行只打印5个数;

import java.util.*;
class demo{
    public static void main(String[] args){
        int count = 0;
        for (int i = 1; i < 1001; i++){
            if(i%3==2&&i%5==3&&i%7==2){
                System.out.print(i+"\t");
                count++;
                if(count==5){
                    System.out.println("\n");
                    count = 0;
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

任务二:

输出 99 乘法表;

import java.util.*;
class demo{
    public static void main(String[] args){
        int i = 0;
        int j = 0;
        for (i = 1; i < 10;i++){
            for (j = 1; j <= i;j++){
                System.out.print(j+" * "+i+" = "+(i*j)+" "); 
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

三个关键字

break

  • 在 switch 中使用,用来防止 case 穿透;

  • 在循环中使用,用来跳出整个循环;

    循环有两个终止的情况:一是循环条件不满足,二是遇到了break

continue

  • 在循环中使用,用来结束本次循环,继续下一次循环;

return

  • 在方法里经常看到 return ,方法里的 return 起到的是返回的作用;
  • 目前在循环中出现的 return ,它不只是结束了循环,而是结束了整个循环所在的方法;

关键字和嵌套循环

break:结束最近的那个整个循环;

continue:结束最近的那个当次循环;

return:结束掉循环所在的整个函数;

实例再证:

打印出1000以内的素数:

import java.util.*;
class demo{
    public static void main(String[] args){
        int count = 1;
        for(int i=1; i < 1000;i++){
        boolean b = false;
            for(int j=2; j < i;j++){
                if (i%j==0){
                    b = true;
                    break; //能够提前结束循环,简化运算
                }
            }
            if (!b){
                System.out.print(i+" ");
                count++;
                if(count==20){
                    System.out.println();
                    count = 1;
                }
            }
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

循环标签:

只适用于给循环打上标签,目的是使用 break 或 continue 时选择性打破循环;

break 正常代码:

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=1; i < 10;i++){
            for (int j=1; j <= 10;j++){
                if (j%4==0){
                    break;
                }
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

break 强制代码(需要加一个标识符,符名自取):

import java.util.*;
class demo{
    public static void main(String[] args){
        good:for (int i=1; i < 10;i++){ //循环标识符添加在循环之前
            for (int j=1; j <= 10;j++){
                if (j%4==0){
                    break good; //结束时也要带上标识符
                }
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

continue 正常代码:

import java.util.*;
class demo{
    public static void main(String[] args){
        for (int i=1; i < 10;i++){ 
            for (int j=1; j <= 10;j++){
                if (j%4==0){
                    continue; 
                }
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

continue 强制代码:

import java.util.*;
class demo{
    public static void main(String[] args){
        good:for (int i=1; i < 10;i++){ //循环标识符添加在循环之前
            for (int j=1; j <= 10;j++){
                if (j%4==0){
                    continue good; //结束时也要带上标识符
                }
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
}

打印效果如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

下一章:由浅到深认识Java语言(7):方法(函数)

  • 26
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值