Java基础语法2
# 顺序结构
程序从上到下依次地执行,中间没有任何判断和跳转。
System.out.println("程序开始");
System.out.println("起床");
System.out.println("洗漱");
System.out.println("开车");
System.out.println("工作");
System.out.println("下班");
System.out.println("睡觉");
System.out.println("程序结束");
分支结构
if
int age = 34234;
if (age < 0 || age >= 150) {
System.out.println("妖怪!");
} else {
if (age >= 60) {
System.out.println("老年");
} else if (age >= 40) {
System.out.println("壮年");
} else if (age >= 20) {
System.out.println("青年");
} else {
System.out.println("未成年");
}
}
switch
String color = "green";
switch (color) {
case "red":
System.out.println("红色");
break;
case "yellow":
System.out.println("黄色");
break;
case "green":
System.out.println("绿色");
break;
case "white":
System.out.println("白色");
break;
default:
System.out.println("花色");
break;
}
总结:if和switch很像,具体什么场景使用什么语句?
- 判断的值不多或者是固定的值,使用switch
- 对于区间判断,使用if
Scanner
import java.util.Scanner;//1.导包
//2.创建扫描器对象
Scanner sc = new Scanner(System.in);
System.out.print("输入你名字:");
String name = sc.next();
System.out.print("输入你年龄:");
int age = sc.nextInt();
System.out.print("输入你的性别:");
char gender = sc.next().charAt(0);
System.out.print("输入你的成绩:");
double score = sc.nextDouble();
System.out.println("名字 = " + name);
System.out.println("年龄 = " + age);
System.out.println("性别 = " + gender);
System.out.println("成绩 = " + score);
循环结构
while
int i = 1;
while (i<=5){
System.out.println("hi");
i++;
}
do while
int i = 1;
do {
System.out.println("hi");
i++;
} while (i <= 5);
for
for (int i = 1; i <= 5; i++) {
System.out.println("hi");
}
总结:while 和 do-while 的区别?
- while:先判断循环条件,再执行循环体
- do-while:先执行循环体,再判断循环条件,至少执行一次
特殊流程控制
break
for (int i = 1; i <= 40; i++) {
if (i == 13) {
break;//跳出循环
}
System.out.println(i);
}
continue
for (int i = 1; i <= 40; i++) {
if (i == 13) {
continue;//跳过当前循环,执行下次循环
}
System.out.println(i);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~