java switch语句在很多情况下简化了 [英] java switch statement many cases simplified

查看:45
本文介绍了java switch语句在很多情况下简化了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以让我们说一个 switch 语句是,

So lets say a switch statment is,

switch (month) {  
    case 1: monthString = "January";  
        break;  
    case 2: monthString = "February";  
        break;  
    case 3: monthString = "March";  
        break;  
    case 4: monthString = "April";  
        break;  
    case 5: monthString = "May";  
        break;  

是否可以将其缩短为类似

Is it possible to shorten that to something like

switch (month) {
    cases 1-3: monthString = "January";
        break;
    case 4-5: monthString = "April";
        break;

所以在一个案例下有多个案例编号?我正在这样做,因为我有 100 个案例.30 导致一个答案,20 到另一个,5 到另一个等等......所以如果我可以使用多个案例,我应该大量减少大部分代码.我还应该在每种情况下提到我想做一些事情,如果我使用一系列 if else 语句,它只会让我执行一个操作,所以我似乎无法走那条路.谢谢你的帮助!抱歉,我是新手!

So that multiple case numbers are under one case? I'm doing it as I have 100 cases. 30 lead to one answer, 20 to another, 5 to another etc... so if I can use multiple cases I should cut down the bulk of the code by alot. I should also mention at each case I will want to do a few things and if I use a series of if else statements it only lets me perform one action so I cannot seem to go that route. Thanks for any help! sorry I'm new at this!

推荐答案

是否可以将其缩短为类似

Is it possible to shorten that to something like

Java 教程 中有更好的解释 switch 语句

It's better explained in Java Tutorial The switch Statement

是的,你可以做到.

一些关键点:

  • 不要忘记添加 break 语句.
  • 在所有分组案例之后添加单个 break 语句.
  • 永远不要忘记添加 default 案例.
  • Don't forget to add the break statement.
  • Add single break statement after all grouped cases.
  • Never forget to add default case as well.

示例代码:

    int month = 1;
    String monthString = null;

    switch (month) {
        case 1:
        case 2:
        case 3:
            monthString = "January";
            break;
        case 4:
        case 5:
            monthString = "April";
            break;
        ...
        default:
            ...
    }

这篇关于java switch语句在很多情况下简化了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆