JAVA的控制语句

控制语句

分为顺序、选择和循环

顺序结构

先执行a,再执行b

条件判断结构

如果......则.......

循环结构

如果.....则重复执行

条件判断结构(选择结构)

if单分支结构

语法结构:

if(布尔表达式){

语句块

}

注:如果if后不跟花括号{},只能作用域第一条语句。

前言:

Math类的使用

Math.random()用于产生0~1之间的double类型的随机数,但不包括1

int i = (int)(6 * Math.random());   //产生[0,5]之间的随机整数
掷骰子游戏
/**
 * 掷骰子游戏
 * 游戏规则:
 * 1.如果三次的值加起来大于15,则输出 手气不错哦 ^.^
 * 2.如果三次的值之和10~15之间,输出 手气一般哦 ~.~
 * 3.如果三次得值之和小于10,输出 手气好差 =.=
 * */
public class game {
    public static void main(String[] args){
        int i =(int) (Math.random() * 6 + 1);
        int j =(int) (Math.random() * 6 + 1);
        int k =(int) (Math.random() * 6 + 1);
        int count = i + j + k;
        System.out.println("first score: " + i);
        System.out.println("first score: " + j);
        System.out.println("first score: " + k);
​
        if(count > 15){
            System.out.println("手气不错哦 ^.^,再来一次波!");
        }
        if(count >= 10 && count < 15){
            System.out.println("手气一般哦 ~.~,再接再厉!");
        }
        if(count < 10){
            System.out.println("手气好差 =.=,溜溜球咯~");
        }
        System.out.println("今天总得分:" + count);
    }
}

结果随机:

if-else双分支结构

语法结构:

if(布尔表达式){

语句块1

}else{

语句块2

}

public class TestIf02 {
    public static void main(String[] args) {
        double r = 4 * Math.random();
        double area = 3.14 * r * r;
        double circle = 2 * Math.PI * r;
​
        System.out.println("半径:" + r);
        System.out.println("周长:" + area);
        System.out.println("面积:" +circle);
​
        if(area > circle){
            System.out.println("周长比面积小");
        }else{
            System.out.println("周长比面积大");
        }
    }
}

if-else与条件运算符效果相似:

       //条件运算符
       int a = 3 ,b =5;
        int c = a > b ? a:b;
        System.out.println(c);
        //等同于if-else:
        if(a > b){
            c = a;
        }else{
            c = b;
        }
        System.out.println(c);
if-else if-else多分支结构

语法结构:

if(布尔表达式1){

语句块1

}else if(布尔表达式2){

语句块2

}......

else if(布尔表达式n){

语句块n

}else{

......

}

相对于if单分支更简洁方便

年龄判定
/**
 * 年龄判定
 * 游戏规则:
 * 1.15岁以下(不包括15):儿童
 * 2.15~24:青年
 * 3.25~44:中年
 * 4.45~65:中老年
 * 5.66~90:老年
 * 6.91~99:老寿星
 * 7.100~109:百岁老人
 * 8.110以上:好小汁!!不死神仙!
 * */
public class TestIf03 {
    public static void main(String[] args){
        int age = (int)(100 * Math.random());
        System.out.println(age);
​
        if(age < 15){
            System.out.println("儿童");
        }else if(age < 25){
            System.out.println("青年");
        }else if(age < 44){
            System.out.println("中年");
        }else if(age < 65){
            System.out.println("中老年");
        }else if(age < 90){
            System.out.println("老年");
        }else if (age < 100){
            System.out.println("老寿星");
        } else if (age < 109){
            System.out.println("百岁老人");
        }else{
            System.out.println("好小汁!!不死神仙!");
        }
        }
​
    }
​
switch分支结构

语法结构:(多值判断)

switch(表达式){

case 值1:

语句块1;

break;

case 值2:

语句块2;

break;

.............

default:

默认语句块;

}

注:

  • switch会根据表达式的值从相匹配的case标签处开始执行,一直执行到break处或switch的末尾,如果表达式的值与任一case值不匹配,则进入default语句

  • switch中表达式的值是int(byte、short、char都可,long不行)、枚举、字符串

随机年级
//switch实现:
public class TestSwitch {
    public static void main(String[] args) {
        int grade = (int)(Math.random() * 4);
        switch (grade){
            case 1:
                System.out.println("大一");
                break;
            case 2:
                System.out.println("大二");
                break;
            case 3:
                System.out.println("大三");
                break;
            default:
                System.out.println("大四");
                break; //可写可不写
        }
    }
}
​
//if-else if实现:
 if (grade == 1){
            System.out.println("大一");
        } else if (grade == 2) {
            System.out.println("大二");
        } else if (grade == 3) {
            System.out.println("大三");
        }else {
            System.out.println("大四");
        }
判断月份属于某个季节
public class TestSwitch01 {
    public static void main(String[] args) {
        int month = (int)(Math.random() * 12 +1);
        //if-else if实现
        if(month == 3 || month == 4 || month == 5){
            System.out.println("春天来咯~ ^.^");
        } else if (month == 6 || month == 7 || month == 8) {
            System.out.println("是夏天!( •̀ ω •́ )!");
        } else if (month == 9 || month == 10 || month == 11) {
            System.out.println("好冷>.<,冬天到了");
        } else {
            System.out.println("秋天,看枫叶🍁");
        }
​
        //switch实现:
        switch (month){
            case 3:
            case 4:
            case 5:
                System.out.println("春天来咯~ ^.^");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println("是夏天!( •̀ ω •́ )!");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println("好冷>.<,冬天到了");
                break;
            default:
                System.out.println("秋天,看枫叶🍁");
                break;
        }
    }
}

循环结构
  • 当型:当布尔表达式为true时,反复执行语句,为false才停止执行,eg: while和for循环

  • 直到型:先执行某语句,再判断布尔表达式,为true再执行,反复执行,知道布尔表达式条件为false才停止循环,eg: do-while循环

while循环

语法结构:

while(布尔表达式){

循环体;

}

  • 在循环刚开始时,会计算一次"布尔表达式的"的值,条件为真,执行循环体,对于后来每一次额外的循环,都会在开始前重新计算一次

  • 语句中应有使循环趋向于结束的语句,否则会无限循环---"死循环"

  //求累加和:从1加到100
        int b = 1;
        int sum = 0;
        while(b < 101){
            sum += b;
            b++;
        }
        System.out.println(sum);
for循环

语法结构:

for(初始表达式;布尔表达式;迭代因子){

循环体;

}

  • 初始化部分设置:循环变量的初值

  • 条件判断部分:布尔表达式

  • 迭代因子:控制循环变量的增减

求累加和
public class TestFor {
    public static void main(String[] args) {
        for(int a = 0;a < 6;a++){
            System.out.println("I Love U!❤");
        }

        int sum = 0;
        for(int n = 0;n <= 100;n++){
            sum = sum +n;
        }
        System.out.println(sum);

        // 输出9~0之间的数
        for(int b = 9;b >= 0;b--){
            System.out.println(b + "\t");
        }
        System.out.println(); // 换行
        // 输出90~1之间能被3整除的数
        for(int c = 90;c >=0;c--){
            if(c % 3 == 0){
                System.out.println(c + "\t");
            }
        }
    }
}
do-while循环

语法结构:

do{

循环体;

}while(布尔表达式);

先执行再判断

求累加和
public class TestDoWhile {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        do{
            sum += i;
            i++;
        }while(i < 101);  //注意分号不能省略
        System.out.println(sum);
    }
}
while与do-while的区别

while:先判断再执行

do-while:先执行再判断,循环体至少被执行一次

练习1
  • 求100以内总数和及奇偶数之和

public class TestOddEven {
    public static void main(String[] args) {
        int sum = 0;
        int oddsum = 0;
        int evensum = 0;
        for(int i = 0;i <= 100;i++){
            sum += i;
            if(i % 2 == 0){
                evensum += i;
            }else{
                oddsum += i;
            }
        }
        System.out.println(sum);
        System.out.println(oddsum);
        System.out.println(evensum);

        // while循环
        int i = 0;
        int sum2 = 0;
        int oddSum = 0;
        int evenSum = 0;
        while(i <= 100){
            sum2 += i;
              if(i % 2 == 0){
                evenSum += i;
            }else{
                oddSum += i;
            }
            i++;
        }
        System.out.println(sum2);
        System.out.println(oddSum);
        System.out.println(evenSum);
    }
}
练习2
  • 使用while/for循环0~130之间的数字,每行显示5个数字

public class TestDisplay {
    public static void main(String[] args) {
        // while 循环实现
        int n = 0;
        int count = 0;
        while(n <= 130){
            // 换行实现
            if(n % 5 == 0){
                System.out.println();
            }
            System.out.print(n + "\t");
            n++;
            // 计数器实现
            System.out.print(n);
            count ++;
            if(count == 5) {
                System.out.println();
                count = 0;
            }
            n++;
        }
        
        // for循环实现
        for(int a = 0;a <= 130;a++){
            if(a % 5 == 0){
                System.out.println();
            }
            System.out.print(a + "\t");
        }
    }
}


嵌套循环

循环语句内部,再写一个或多个循环,称为循环嵌套。一般是两层

练习3

打印多行,第一行对应的数字为1,第2行为2.....以此类推

public class TestLoop {
      public static void main(String[] args) {
          for(int a = 0;a <= 5;a++) {
             for (int i = 1; i <= 5; i++) {
                System.out.print(a + "\t");
             }
             System.out.println();
          }
      }
}

练习4

使用嵌套打印九九乘法表

 for(int b = 1;b <= 9;b++) {
		  for (int i = 1; i <= b; i++) {
			System.out.print(i + "*" + b + "=" + (i * b) + "\t"); 
            // System.out.print(i + "*" + b + "=" + (i * b < 10 ?" "+(i * b):i * b) + "\t");
			// (i * b < 10 ?" "+(i * b):i * b) 个位数时在前面加一个空格,否则不加
		  }
		  System.out.println();
	    }

练习5

使用嵌套循环输出五行*,一行5个

public class PrintStar {
    public static void main(String[] args) {
	  for(int b = 0;b < 5;b++) {
		for (int i = 0; i < 5; i++) {
		    System.out.print("*" + "\t");
		}
		System.out.println();
	  }
    }
}

练习6

使用嵌套循环交替打印"#"、"*",一行5个

public class PrintStar02 {
    public static void main(String[] args) {
	  // 循环嵌套实现
		for (int b = 0; b < 5; b++) {
		    for (int i = 0; i < 5; i++) {
			  if ((b + i) % 2 == 0) {
				System.out.print("*" + "\t");
			  } else {
				System.out.print("#" + "\t");
			  }
		    }
		    System.out.println();
		}
		// 计数器实现
		int counter = 0; // 计数器,用于交替打印字符

		for (int i = 0; i < 5; i++) { // 外层循环,控制行数
		    for (int j = 0; j < 5; j++) { // 内层循环,控制每行的字符数
			  if (counter % 2 == 0) {
				System.out.print("*\t"); // 当计数器为偶数时打印*
			  } else {
				System.out.print("#\t"); // 当计数器为奇数时打印#
			  }
			  counter++; // 每次打印一个字符后,计数器加1
		    }
		    System.out.println(); // 每打印完一行后换行
		}

	  }
}

break语句和continue语句
  • break用于强制退出整个循环

  • continue用于结束本次循环,继续下一次

练习7

产生100以内的随机数,直到随机数为99时停止

public class TestBreak {
    public static void main(String[] args) {
	  int total = 0;  // 循环的总次数
	  while(true) {
		total ++;
		int n = (int) (Math.random() * 101);
		System.out.println(n);
		if(n == 99) {
		    break;
		}
	  }
	  System.out.print("循环次数:"+total);
    }
}

练习8

输出100~150内不能被3整除的数,且每行输出5个

public class TestContinue {
    public static void main(String[] args) {
	  int count = 0;
	  for(int n = 100;n <= 150;n++) {
/*		if(n % 3 != 0){
		    System.out.print(n+"\t");
	  }*/
		// continue:
		if(n % 3 == 0){
		    continue;
		}
		System.out.print(n+"\t");
		count++;
		if(count == 5){
		    System.out.println();
		    count = 0;
		}
		}
	  }
    }

带标签的continue语句
练习9

控制嵌套循环跳转(打印101~150之间所有的质数)

public class TestContinueLabel {
    public static void main(String[] args) {
	 outer:for(int n = 101;n <= 150;n++){
		for(int i = 2; i < n;i++){
		    if(n % i == 0){   // 余数为0就不用算,它不是质数
			  continue outer; // 符合某条件,跳到外部循环继续
		    }
		}
	     System.out.print(n+"\t");
	  }
    }
}

年薪计算器
  • 通过键盘输入用户的月薪,每年是几个月薪水

  • 输出用户的薪水

  • 输出一行字:"如果年薪超过10万,恭喜你超越90%的人!",如果年薪超过20万,"恭喜你超过98%的人!"

  • 直到键盘输入数字88,退出程序(break实现)

  • 键盘输入66,则这个用户退出计算不显示"恭喜...",直接显示"重新开计算...",然后计算下一个用户的年薪

import java.util.Scanner;

public class SalaryCalculate {
    public static void main(String[] args) {
	  Scanner scanner = new Scanner(System.in);
	  System.out.println("**********年薪计算器***********");
	  System.out.println("·输入88退出程序\n·输入66,计算下一位年薪\n");


	  while(true){
		System.out.println("请输入您的月薪:");
		long salary = scanner.nextInt();
		System.out.println("请输入您的月份:");
		int month = scanner.nextInt();
		long yearSalary = salary * month;
		System.out.println("您的年薪是:" + yearSalary);
		if(yearSalary >= 200000){
		    System.out.println("恭喜你超越98%的人!");
		}else if(yearSalary >= 100000){
		    System.out.println("恭喜你超越90%的人!");
		}else{
		    System.out.println("要加油啦!!");
		}

		System.out.println("输入88退出系统,输入66继续计算!");
		int command = scanner.nextInt();
		if(command == 88){
		    System.out.println("系统退出!");
		    break;
		}else if(command == 66){
		    System.out.println("重新开始计算年薪");
		    continue;
		}
	  }
    }
}
个税计算器
  • 通过键盘输入用户的月薪

  • 百度搜索个税计算方式,计算出应缴纳的税款

  • 直到键盘输入88,退出程序

级数应纳税所得额税率(%)速算扣除数
1不超过3000元的部分30
23000~12000的部分10210
312000~25000的部分201410
425000~35000的部分252660
535000~55000的部分304410
655000~80000的部分357160
7超过80000的部分4515160

import java.util.Scanner;
​
public class TaxCalculate {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("***********个税计算器**********");
        System.out.println("输入88退出程序");
​
        while(true){
           System.out.println("请输入您的月薪:");
           double monthSalary = scanner.nextDouble();
           double jiaoTax = monthSalary - 5000;
           double taxRate = 0;
​
           if(monthSalary < 5000){
               System.out.println("个税起征点为5000,您不需要交税!");
           }else if(jiaoTax <= 3000){
               taxRate = jiaoTax * 0.03;
               monthSalary = monthSalary - taxRate;
           }else if(jiaoTax > 3000 && jiaoTax <= 12000){
               taxRate = jiaoTax * 0.1 - 210;
               monthSalary = monthSalary - taxRate;
           }else if(jiaoTax > 12000 && jiaoTax <= 25000){
               taxRate = jiaoTax * 0.2 - 1410;
               monthSalary = monthSalary - taxRate;
           }else if(jiaoTax > 25000 && jiaoTax <= 35000){
               taxRate = jiaoTax * 0.25 - 2660;
               monthSalary = monthSalary - taxRate;
           }else if(jiaoTax > 35000 && jiaoTax <= 55000){
               taxRate = jiaoTax * 0.3 - 4410;
               monthSalary = monthSalary - taxRate;
           }else if(jiaoTax > 55000 && jiaoTax <= 80000){
               taxRate = jiaoTax * 0.35 - 7610;
               monthSalary = monthSalary - taxRate;
           }else{
               taxRate = jiaoTax * 0.45 - 15160;
               monthSalary = monthSalary - taxRate;
           }
           System.out.println("个人应纳所得税:" + taxRate);
           System.out.println("您的月工资最终是:" + monthSalary);
​
           System.out.println("输入88退出程序.\n输入66继续计算下一位个税及月工资");
           int command = scanner.nextInt();
           if(command == 88){
               System.out.println("程序终止!");
               break;
           }else if(command == 66){
               System.out.println("请继续输入您的月薪:");
               continue;
           }
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/494794.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

极简wordpress网站模板

Pithy设计师wordpress网站模板 精练简洁的wordpress模板&#xff0c;设计师或设计工作室展示型网站模板。 https://www.jianzhanpress.com/?p6329

11.Notepad++

文章目录 一、下载和安装设置练习 以前在记事本上写的代码看上去有点累&#xff0c;因为所有的单词看上去都是黑色的&#xff0c;并且当代码出现问题后&#xff0c;它提示第三行&#xff0c;我们还需要一行一行去数。这些问题都可以由一个高级记事本&#xff1a; Notepad 来解…

Ceph——部署

Ceph简介 Ceph是一款开源的 SDS 分布式存储&#xff0c;它具备极高的可用性、扩展性和易用性&#xff0c;可用于存 储海量数据 Ceph的存储节点可部署在通用服务器上&#xff0c;这些服务器的 CPU 可以是 x86 架构的&#xff0c;也可以 是 ARM 架构的。 Ceph 存储节点之间相互…

深入探讨分布式ID生成方案

&#x1f388;&#x1f388;作者主页&#xff1a; 喔的嘛呀&#x1f388;&#x1f388; &#x1f388;&#x1f388;所属专栏&#xff1a;python爬虫学习&#x1f388;&#x1f388; ✨✨谢谢大家捧场&#xff0c;祝屏幕前的小伙伴们每天都有好运相伴左右&#xff0c;一定要天天…

【Functional Affordances】如何确认可抓取的区域?(前传)

文章目录 1. 【Meta AI】Emerging Properties in Self-Supervised Vision Transformers2. 【Meta AI】DINOv2: Learning Robust Visual Features without Supervision3. 【NeurIPS 2023】Diffusion Hyperfeatures: Searching Through Time and Space for Semantic Corresponden…

网安学习笔记-day9,DNS服务器介绍

文章目录 DNS服务器部署域名介绍及分类DNS解析解析过程1.递归查询2.迭代查询 DNS服务器部署准备阶段安装DNS服务 部署过程在另一台虚拟机查看是否能解析到baidu.com的地址测试解析 转发器 扩展命令 DNS服务器部署 DNS(Domain Name System) 域名介绍及分类 常用的www.baidu.c…

【unity】如何汉化unity编译器

在【unity】如何汉化unity Hub这篇文章中&#xff0c;我们已经完成了unity Hub的汉化&#xff0c;现在让我们对unity Hub安装的编译器也进行下汉化处理。 第一步&#xff1a;在unity Hub软件左侧栏目中点击安装&#xff0c;选择需要汉化的编译器&#xff0c;再点击设置图片按钮…

stitcher类实现多图自动拼接

效果展示 第一组&#xff1a; 第二组&#xff1a; 第三组&#xff1a; 第四组&#xff1a; 运行代码 import os import sys import cv2 import numpy as npdef Stitch(imgs,savePath): stitcher cv2.Stitcher.create(cv2.Stitcher_PANORAMA)(result, pano) stitcher.st…

自动化面试常见算法题!

1、实现一个数字的反转&#xff0c;比如输入12345&#xff0c;输出54321 num 12345 num_str str(num) reversed_num_str num_str[::-1] reversed_num int(reversed_num_str) print(reversed_num) # 输出 54321代码解析&#xff1a;首先将输入的数字转换为字符串&#xff…

ARMday7作业

实现三个按键的中断&#xff0c;现象和代码 do_ipr.c #include "stm32mp1xx_gic.h" #include "stm32mp1xx_exti.h" extern void printf(const char *fmt, ...); unsigned int i 0; void do_irq(void) {//获取要处理的中断的中断号unsigned int irqnoGI…

离线数仓(八)【DWD 层开发】

前言 1、DWD 层开发 DWD层设计要点&#xff1a; &#xff08;1&#xff09;DWD层的设计依据是维度建模理论&#xff08;主体是事务型事实表&#xff08;选择业务过程 -> 声明粒度 -> 确定维度 -> 确定事实&#xff09;&#xff0c;另外两种周期型快照事实表和累积型…

信号处理--情绪分类数据集DEAP预处理(python版)

关于 DEAP数据集是一个常用的情绪分类公共数据&#xff0c;在日常研究中经常被使用到。如何合理地预处理DEAP数据集&#xff0c;对于后端任务的成功与否&#xff0c;非常重要。本文主要介绍DEAP数据集的预处理流程。 工具 图片来源&#xff1a;DEAP: A Dataset for Emotion A…

如何备考2025年AMC8竞赛?吃透2000-2024年600道真题(免费送题

最近有家长朋友问我&#xff0c;现在有哪些类似于奥数的比赛可以参加&#xff1f;我的建议可以关注下AMC8的竞赛&#xff0c;类似于国内的奥数&#xff0c;但是其难度要比国内的奥数低一些&#xff0c;而且比赛门槛更低&#xff0c;考试也更方便。比赛的题目尤其是应用题比较有…

肿瘤靶向肽 iRGD peptide环肽 1392278-76-0 c(CRGDKGPDC)

RGD环肽 c(CRGDKGPDC)&#xff0c;iRGD peptide 1392278-76-0 结 构 式&#xff1a; H2N-CRGDKGPDC-OH(Disulfide Bridge:C1-C9) H2N-Cys-Arg-Gly-Asp-Lys-Gly-Pro-Asp-Cys-COOH(Disulfide Bridge:Cys1-Cys9) 氨基酸个数&#xff1a; 9 C35H57N13O14S2 平均分子量:…

聊聊低代码产品的应用场景

随着数字化转型的不断深入&#xff0c;企业对于快速开发和迭代软件应用的需求也越来越迫切。而在这样的背景下&#xff0c;低代码产品应运而生&#xff0c;成为了一种热门的技术解决方案。本文将解读低代码产品的定义并探讨其应用场景。 一、低代码产品的定义 低代码产品是一种…

企业计算机服务器中了rmallox勒索病毒怎么办,rmallox勒索病毒解密流程步骤

在网络技术飞速发展的时代&#xff0c;越来越多的企业离不开网络办公&#xff0c;通过网络开展各项工作业务成为企业的常态&#xff0c;这也被国外众多黑客组织盯上的原因&#xff0c;近期&#xff0c;网络勒索病毒攻击的事件频发&#xff0c;越来越多的企业开始重视企业数据安…

Rust语言中Regex正则表达式,匹配和查找替换等

官方仓库&#xff1a;https://crates.io/crates/regex 文档地址&#xff1a;regex - Rust github仓库地址&#xff1a;GitHub - rust-lang/regex: An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear tim…

leetcode:2138. 将字符串拆分为若干长度为 k 的组(python3解法)

难度&#xff1a;简单 字符串 s 可以按下述步骤划分为若干长度为 k 的组&#xff1a; 第一组由字符串中的前 k 个字符组成&#xff0c;第二组由接下来的 k 个字符串组成&#xff0c;依此类推。每个字符都能够成为 某一个 组的一部分。对于最后一组&#xff0c;如果字符串剩下的…

【SAP2000】在框架结构中应用分布式面板荷载Applying Distributed Panel Loads to Frame Structures

在框架结构中应用分布式面板荷载 Applying Distributed Panel Loads to Frame Structures 使用"Uniform to Frame"选项,可以简单地将荷载用于更多样化的情况。 With the “Uniform to Frame” option, loads can be easily used for a greater diversity of situat…

如何高效阅读嵌入式代码

大家好&#xff0c;今天给大家介绍如何高效阅读嵌入式代码&#xff0c;文章末尾附有分享大家一个资料包&#xff0c;差不多150多G。里面学习内容、面经、项目都比较新也比较全&#xff01;可进群免费领取。 高效阅读嵌入式代码需要一些技巧和实践经验。以下是一些建议&#xff…
最新文章