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: 我在循环

相关推荐
凌波粒1 天前
LeetCode--383.赎金信(哈希表)
java·算法·leetcode·散列表
liulilittle1 天前
OPENPPP2 1.0.0.26145 正式版发布:内核态 SYSNAT 性能飞跃 + Windows 平台避坑指南
开发语言·网络·c++·windows·通信·vrrp
贺小涛1 天前
VictoriaMetrics深度解析
java·网络·数据库
消失的旧时光-19431 天前
C++ 网络服务端主线:从线程池到 Reactor 的完整路线图
开发语言·网络·c++·线程池·并发
疯狂打码的少年1 天前
【Day02 Java转Python】Python的ArrayList: list与tuple的“双面人生
java·python·list
回到原点的码农1 天前
Spring Boot 3.3.4 升级导致 Logback 之前回滚策略配置不兼容问题解决
java·spring boot·logback
打瞌睡的朱尤1 天前
js复习--考核
开发语言·前端·javascript
wjs20241 天前
SQL SELECT DISTINCT 详解
开发语言
jwt7939279371 天前
SpringBoot实现异步调用的方法
java·spring boot·spring