Java Switch和有趣代码

本文详细介绍了Java中的switch...case结构,强调了其效率高、结构清晰的优点和只能判断整数的限制。通过一个银行流程的示例代码,展示了switch如何用于处理不同情况,包括取款、存款、查询余额和退卡等功能。代码中体现了break关键字的使用以及default分支的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Switch和有趣代码

switch详解

switch…case结构:多条路

  • 说明:

  • 优点:效率高、结构清晰

  • 缺点:只能对整数判断相等

  • break:跳出switch

  • 没有break就会向下一直运行,直到结束

  • 如果都不符合用default

  • switch可以作用于哪些数据类型上

—byte、short、int、char、String、枚举类型(enum)-------------重要

有趣代码

Haha我自己写的觉得有趣的代码

//银行流程
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int number = 1;
    System.out.println("请选择你的初始资金:");
    int cash_Saved = scan.nextInt();
    while(number==1) {
        System.out.println("请选择功能: 1.取款, 2存款, 3.查询余额 0.退卡");
        int command = scan.nextInt();
        switch (command) {
            case 0: //0.退卡
                System.out.println("好的您的余额是:" + cash_Saved);
                System.out.println("现在退卡");
                number=0;
                break;
            case 1: //1.取款
                System.out.println("你要取多少钱:");
                int cash_Out = scan.nextInt();
                System.out.println("好的现在为您取!!");
                cash_Saved = cash_Saved-cash_Out;
                break;
            case 2: //2存款
                System.out.println("你要存多少钱:");
                int cash_In = scan.nextInt();
                System.out.println("好的现在为您存!!");
                cash_Saved = cash_Saved + cash_In;
                System.out.println("好的您的余额是:" + cash_Saved);
                break;
            case 3: //3.查询余额
                System.out.println("好的您的余额是:" + cash_Saved);
                break;
            default:
                System.out.println("输入错误请重新再输一遍");
                break;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值