JAVA_04_判断与循环

01 if的格式和易错点

python 复制代码
package com.itheima.ifdemo;
/*
if(关系表达式){
语句体;
i计的注意点:
1.大括号的开头可以另起一行书写,但是建议写在第一行的末尾
2.在语句体中,如果只有一句代码,大括号可以省略不写。个人建议,大括号还是不要省略.
3.如果对一个布尔类型的变量进行判断,不要用==号,直接把变量写在小括号即可,例子如下,会导致一直判断为true,最好使用方式2,避免报错
*/
public class IfDemo2 {
    public static void main(string[] args) {
    int number = 20;
    if(number >= 10)
        System.out.println("number大于等于10");

    /*方式1:能运行,但是还差一个=号,经常容易犯这个错误,导致一直判断为true*/
    boolean flag = true;
    if(flag=true)
        System.out.println("flag为true");

    /*方式2:这样更好*/
    boolean flag = true;
    if(flag)
        System.out.println("flag为true");
}
}

格式和C++的三种一样的,第一种if,第二种if else

02 switch

python 复制代码
public class SwitchWithStringOperation {
    public static void main(String[] args) {
        String name = "Alice";
        
        // switch括号内包含字符串运算
        switch (name.toLowerCase()) { // 转换为小写,确保大小写不敏感
            case "alice":
                System.out.println("Hello, Alice!");
                break;
            case "bob":
                System.out.println("Hi, Bob!");
                break;
            default:
                System.out.println("Welcome, stranger!");
                break;
        }
    }
}

03 switch其他知识

(1)default 的位置和省略

  • default可以写在 switch里的任何位置(开头、中间、结尾)
  • 可以省略 default(不写),意味着当所有 case都不匹配时,什么都不做

(2)case 穿透

  • 当 case后没有 break时,程序会继续执行下一个 case的代码,直到遇到 break或 switch结束。

(3)switch 新特性(Java 14+)

  • 箭头语法(->):可以省略 break,自带穿透阻断。
  • 多值匹配:一个 case可以匹配多个值,用逗号分隔。
java 复制代码
int day = 3;
switch (day) {
    case 1, 2, 3, 4, 5 -> System.out.println("工作日");
    case 6, 7 -> System.out.println("周末");
    default -> System.out.println("无效日期");
}
// 输出:工作日

04循环

感觉没什么好记录的,跟c++一样的

  • for
  • while
  • do...while

例子:

python 复制代码
int x = 0;

// for:明确 3 次
for (int i = 0; i < 3; i++) {
    System.out.println("for: 我在循环");
}

// while:条件满足就继续
while (x < 3) {
    System.out.println("while: 我在循环");
    x++;
}

// do...while:至少一次
x = 0;
do {
    System.out.println("do...while: 我在循环");
    x++;
} while (x < 3);

结果:

for: 我在循环

for: 我在循环

for: 我在循环

while: 我在循环

while: 我在循环

while: 我在循环

do...while: 我在循环

do...while: 我在循环

do...while: 我在循环

相关推荐
Volunteer Technology1 小时前
LangGraph的WorkFlow(一)
java·服务器·windows
懒惰成性的1 小时前
11.Java的String类
java·开发语言
FoldWinCard2 小时前
Python 第三次作业
java·服务器·python
傻啦嘿哟2 小时前
Python列表排序:用key参数掌控排序规则
java·开发语言
你的冰西瓜2 小时前
C++ STL算法——修改序列算法
开发语言·c++·算法·stl
大尚来也2 小时前
解决 IDEA 运行 Spring Boot 测试时“命令行过长”错误的终极方案
java·spring boot·intellij-idea
froginwe112 小时前
装饰器模式
开发语言
云姜.2 小时前
如何在idea上使用数据库
java·数据库·intellij-idea
枫叶丹42 小时前
【Qt开发】Qt界面优化(三)-> Qt样式表(QSS) 设置方式
c语言·开发语言·c++·qt·系统架构