switch case怎么写能美观一点
时间: 2023-12-21 08:31:52 浏览: 117
在Java中,switch case语句可以通过使用枚举值来使代码更美观。下面是一个示例代码,展示了如何使用枚举值和switch case语句来实现美观的代码:
```java
// 定义一个枚举类
enum TestObjectEnums {
苹果大厦,
西瓜公寓,
葡萄居所,
哈密瓜楼
}
// 使用switch case语句进行筛选
for (TestObject to : queryList) {
switch (to.getCategoryCode()) {
case 苹果大厦:
apple.add(to);
break;
case 西瓜公寓:
waterMelon.add(to);
break;
case 葡萄居所:
grape.add(to);
break;
case 哈密瓜楼:
hamiMelon.add(to);
break;
default:
break;
}
}
```
这样,通过使用枚举值,我们可以在switch case语句中直接使用枚举值的名称,使代码更加清晰和易读。
相关问题
如何让用c++写一个好看一点的菜单
在C++中创建一个美观的菜单通常涉及控制台输入输出、字符串处理以及一些简单的用户界面设计。以下是一个基本的例子,展示了如何使用循环结构和格式化输出来打造一个简单的命令行菜单:
```cpp
#include <iostream>
#include <string>
// 定义菜单选项
enum MenuOption {
OPTION_EXIT,
OPTION_OPEN_FILE,
OPTION_SAVE_FILE,
NUM_OPTIONS
};
void display_menu() {
std::cout << "----------------------------------------" << std::endl;
std::cout << "| 1. 打开文件 | 2. 保存文件 |" << std::endl;
std::cout << "| 0. 退出 | |" << std::endl;
std::cout << "----------------------------------------" << std::endl;
}
int main() {
int choice;
while (true) {
display_menu();
std::cout << "请输入您的选择(0-" << NUM_OPTIONS - 1 << "): ";
std::cin >> choice;
switch (choice) {
case OPTION_EXIT:
std::cout << "感谢使用,再见!" << std::endl;
return 0;
case OPTION_OPEN_FILE:
// 实现打开文件功能
break;
case OPTION_SAVE_FILE:
// 实现保存文件功能
break;
default:
std::cout << "无效的选择,试试看其他选项吧!" << std::endl;
}
}
}
```
在这个例子中,我们首先定义了一个枚举类型的菜单项,然后在`display_menu`函数中通过控制台输出创建菜单样式。主程序部分则通过接收用户的输入并使用switch-case结构来处理不同的菜单选择。
switch流程图怎么画
### 绘制 Switch 语句的流程图
#### 流程图基本元素
为了清晰展示 `switch` 语句的工作原理,可以采用标准的流程图符号。主要使用的图形包括:
- **菱形** 表示决策点或条件判断。
- **矩形** 表示具体的操作步骤。
- **平行四边形** 可表示输入/输出操作。
- **箭头线** 连接各个节点,指示程序执行的方向。
#### 创建 Switch 语句的具体流程图实例
假设有一个简单的 Java 程序,它接收用户输入的一个整数并打印对应的星期几名称。以下是此过程的描述以及相应的流程图表征[^2]。
```java
public class WeekdayFinder {
public static String getWeekDay(int dayNumber) {
switch (dayNumber) {
case 1 -> {
return "Monday";
}
case 2 -> {
return "Tuesday";
}
case 3 -> {
return "Wednesday";
}
case 4 -> {
return "Thursday";
}
case 5 -> {
return "Friday";
}
case 6 -> {
return "Saturday";
}
case 7 -> {
return "Sunday";
}
default -> {
throw new IllegalArgumentException("Invalid Day Number");
}
}
}
public static void main(String[] args) {
System.out.println(getWeekDay(3));
}
}
```
##### 对应的流程图结构如下所示:
1. 开始(椭圆)
2. 输入天数编号(平行四边形)
3. 判断是否等于特定值(多个菱形分别对应不同的case情况),例如:
- 如果是,则跳转到返回相应字符串的部分(矩形);
- 否则继续下一个case测试直到遇到default为止。
4. 输出结果(平行四边形)
5. 结束(椭圆)

注意,在实际绘图工具中创建上述流程图时,应当按照实际情况调整布局和样式以确保可读性和美观度。此外,对于更复杂的场景,可能还需要引入额外的控制流机制,比如循环或者嵌套的选择结构等[^3]。
阅读全文
相关推荐

















