当前位置: 首页 > news >正文

【Java基础入门篇】二、控制语句和递归算法

Java基础入门篇


二、控制语句和递归算法

2.1 switch-case多分支选择语句

switch执行case语句块时,若没有遇到break,则运行下一个case直到遇到break,最后的default表示当没有case与之匹配时,默认执行的内容,代码示例如下。

    /**   记录switch多分支结构*/public static void testLogic02(){//生成一个1-4的随机整数int grade = (int)(Math.random()*4)+1;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;}}

补充:对于生成随机数的使用:Math.random()方法会产生0-1之间的double类型的随机数但是不包括1。如果想生成例如[0, 5]的随机整数可以通过:int i = (int)(6 * Math.random());实现。

2.2 if-else语句

if-else语句是最简单且常用的单分支控制语句,当满足if条件时,执行if的内容,否则执行else。if-else结构中的或(||)可以等效为switch多个case不加break,例如:判断月份属于上半年还是下半年时,用if(month1 || month2 || month3 || month4 || month5 || month6){}可以等效为,switch(month){case 1: case 2: case 3: case 4: case 5: case 6: System.out.println(“这是上半年”);break; default …}

    /** 记录if-else控制语句*/public static void testLogic01(){double rand = Math.random();System.out.println("生成一个随机数: " + rand);/*  if单分支(掷骰子游戏)*   定义规则:*   1.如果三次的点数和>15,则手气不错*   1.如果三次的点数和介于10~15之间,则手气一般*   1.如果三次的点数和<10,则手气很差*/// 定义1-6的随机整数try {int i = (int) (6 * Math.random()) + 1;System.out.println("第一个骰子:" + i);Thread.sleep(1000);int j = (int) (6 * Math.random()) + 1;System.out.println("第二个骰子:" + j);Thread.sleep(1000);int k = (int) (6 * Math.random()) + 1;System.out.println("第三个骰子:" + k);int count = i + j + k;System.out.println("三个骰子总计:" + count);if (count >= 15){System.out.println("今天手气不错!再来一把!");}else if (count>=10 && count < 15) {System.out.println("手气一般!再来两把!");}else{System.out.println("手气不行!回家吧");}}catch(Exception e) {System.out.println("Got an exception!");}}

在这里插入图片描述

2.3 for循环语句

循环结构中必须要有让循环趋于结束的变化变量,否则为“死”循环。for循环本质上就是将初始化部分、布尔表达式以及迭代因子放在一行进行展示。

    /**     记录for循环结构*/public static void testLogic03(){System.out.println("For Circle: ");for(int i = 0; i <= 3; i++){  // 初始化部分、布尔表达式、迭代因子System.out.println(i);   // 循环体}}

在这里插入图片描述

2.4 while循环语句

while循环与for循环类似,但是对应的初始化部分、布尔表达式和迭代因子位于循环内部。

   /**     记录while循环结构*/public static void testLogic03(){int a = 0;  //初始化部分System.out.println("While Circle: ");while(a<3){// 布尔表达式System.out.println(a);   // 循环体a++;  // 迭代因子}}

在这里插入图片描述

do-while和while的区别就是,do-while至少执行一次循环体

    /**     记录do-while循环结构*/public static void testLogic03(){System.out.println("Do-While Circle: ");a = 0; //初始化部分do{System.out.println(a); // 循环体a--; // 迭代因子}while (a > 0); // 布尔表达式}

在这里插入图片描述

2.5 循环结构小案例

案例一

要求:使用while/for循环1-130之间的数字,每行显示5个数字

public static void testLogic04(){int j = 5; //定义计数器for(int i = 1;i <= 130; i++){System.out.print(i+"\t");j--;if (j == 0){ //每五个换一次行System.out.println();j = 5;}}}

在这里插入图片描述

案例二

要求:打印输出九九乘法表

    public static void testLogic05(){for(int i = 1;i <= 9;i++){for(int j = 1; j <= i; j++){// System.out.print(j+"x"+i+"="+i*j+"\t");//通过三目运算法控制右对齐System.out.print(j+"x"+i+"="+(i*j < 10 ? (" "+i*j): i*j)+"\t");}System.out.println();}}

在这里插入图片描述

案例三

要求:打印如下所示:

* * * * *

* * * * *

* * * * *

* * * * *

* * * * *

public static void testLogic05(){for(int i = 0;i < 5;i++){for(int j = 0;j < 5; j++){System.out.print("*"+"\t");}System.out.println();}
}

在这里插入图片描述

案例四

要求:打印如下所示:

* # * # *

# * # * #

* # * # *

# * # * #

* # * # *

   public static void testLogic05(){int c = 0; //计数器for(int i = 0;i < 25;i++){if (i % 2 == 0) {System.out.print("*" + "\t");} else {System.out.print("#" + "\t");}c++;while(c == 5) {c = 0;System.out.println();}}}

在这里插入图片描述

2.6 递归算法

递归的思想就是“自己调自己”,需要定义递归头(什么时候结束递归)以及递归体(什么时候调用递归)。递归的优点是算法简单,但是递归会占用大量的系统堆栈,内存耗用多,相较于循环速度会慢的多。

    /**   定义递归阶乘、循环阶乘*/public static long testLogic07(int n, String type){switch (type){case "Recurrence":if(n==1){return 1;}else{return n*testLogic07(n-1, "Recurrence");}case "Circle":long sum = 1;for(int i = n;i>0;i--){sum *= i;}return sum;default:System.out.println("请选择Recurrence或者Circle中的任意一种方法");break;}return 9999;}

在这里插入图片描述

http://www.lryc.cn/news/494334.html

相关文章:

  • PostgreSQL WAL日志膨胀处理
  • 用户该怎么管理维护自己的服务器?
  • 【MYSQL数据库相关知识介绍】
  • 初窥 HTTP 缓存
  • yolov8的深度学习环境安装(cuda12.4、ubuntu22.04)
  • RSA算法和AES算法,哪种更安全
  • Vue教程|搭建vue项目|Vue-CLI新版脚手架
  • kdump调试分析(适用于麒麟,ubuntu等OS)
  • houdini肌肉刷pin点的方法
  • JMeter 并发策略-针对准点秒杀场景的压测实现
  • 龙迅#LT6912适用于HDMI2.0转HDMI+LVDS/MIPI,分辨率高达4K60HZ,支持音频和HDCP2.2
  • RBF神经网络预测结合NSGAII多目标优化
  • 如何看linux系统内核是aarch64 ,还是64-bit
  • 如何通过 ADB 安装 xapk
  • QT:多ui界面显示
  • redis cluster 3主3从部署方案
  • 前端学习笔记之文件下载(1.0)
  • 从技术视角看AI在Facebook全球化中的作用
  • Web 表单开发全解析:从基础到高级掌握 HTML 表单设计
  • Milvus 2.5:全文检索上线,标量过滤提速,易用性再突破!
  • 【webrtc】 mediasoup中m77的IntervalBudget及其在AlrDetector的应用
  • AI数据分析工具(二)
  • 小米路由mini刷PDCN教程补充
  • [巅峰极客 2021]签到
  • 详解SpringCloud集成Camunda7.19实现工作流审批(二)
  • Matlab学习笔记
  • Hexo博客在多个设备同步
  • 淘宝Vision Pro:革新购物体验的沉浸式未来
  • 公链开发中的技术实现路径:构建高效、安全的去中心化网络
  • mac上的建议xftp 工具