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