栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

0基础学Java(5)(switch case 和循环结构)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

0基础学Java(5)(switch case 和循环结构)

1. 分支结构

1.1 switch - case

switch (存储选择选项的变量) {
case 常量1:
// 处理方式1;
break;
case 常量2:
// 处理方式2;
break;
case 常量3:
// 处理方式3;
break;
default:
// 最终处理方式
break;
}

​// switch case
import java.util.Scanner;
 
class Demo1 {
	public static void main(String[] args) {
		// choose 作为用户选项输入临时保存变量
		int choose = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("1. 胡辣汤");
		System.out.println("2. 扁粉菜");
		System.out.println("3. 羊杂汤");
		System.out.println("4. 热干面");
		System.out.println("5. 豆浆+油条");
		System.out.println("6. 凉皮");
		
		choose = sc.nextInt();
		
		switch (choose) {
			case 1:
				System.out.println("8RMB");
				break;
			case 2:
				System.out.println("6RMB");
				break;
			case 3:
				System.out.println("20RMB");
				break;
			case 4:
				System.out.println("5RMB");
				break;
			case 5:
				System.out.println("7RMB");
				break;
			case 6:
				System.out.println("7RMB");
				break;
			default:
				System.out.println("选择错误");
				break;
		}
	}
}

1.2 switch case 使用特征

1.case 之后不允许出现相同变量,CPU无法执行,语法报错。
2.超出 case - break 或者 default - break 语句无法执行,为无效语句,语法报错
3.break 可以省略,case 选择会继续执行到下一个 break 或者整个结构大括号结束
4.default 可以省略,但是不建议省略

2.循环结构
2.1 While 循环结构

// 格式
while () {
// 循环体
// (循环条件修改)
}

​

// while 循环结构
class Demo3 {
	public static void main(String[] args) {
		int num = 10;
		
		while (num > 0) {
			// Ctrl + C 终止 终端运行程序
			System.out.println("阿喵喜欢吃鱼");
			num -= 1; // 循环条件修改/循环条件变更
		}
	}
}

2.3 do while 循环结构

// 格式
do {
// 循环体
// (循环条件修改)
} while ();

​// do while 循环结构
class Demo4 {
	public static void main(String[] args) {
		int num = 10;
		
		do {
			System.out.println("阿喵爱玩游戏");
			num -= 1;
		} while (num > 0);
	}
}

2.4 for 循环结构

for () {
// 循环体
}
在这里插入图片描述

// for 循环
class Demo5 {
	public static void main(String[] args) {
		
		for (int i = 0; i < 10; i++) {
			System.out.println("操练起来!!!");
		}
	}
}
``

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756760.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号