如何更改if-else语句以在java中切换case语句

时间:2015-11-10 06:40:47

标签: java if-statement switch-statement

我的问题是如何更改if-else语句来切换case语句,我做了一些工作,它在netbean中包含错误:

if(result.length <= 2){
            if ((result[0].equals("UC"))||(result[0].equals("uc"))){
                fix = "UC";
            }
            else if ((result[0].equals("LC"))||(result[0].equals("lc"))){
                fix = "LC";
            }
            else
                fix = "error";  
        }else
            fix = "length";

4 个答案:

答案 0 :(得分:1)

试试这个

switch (result[0]) {
    case "UC":
    case "uc":
        fix = "UC";
        break;
    case "LC":
    case "lc":
        fix = "LC";
        break;
    default:
        fix = "error";
}

答案 1 :(得分:0)

if(result.length <= 2){
        switch(result[0]){
                      case "UC":
                      case "uc":
                         fix = "UC";
                         break;
                      case "LC":
                      case "lc":
                         fix = "LC";
                         break;
                      default:
                         fix = "error";
                         break;
           }
      }
      else
        fix = "length";

答案 2 :(得分:0)

另一种解决方案:

switch (Boolean.toString(result.length <= 2)) {
    case "true":
        switch (result[0]) {
            case "UC":
            case "uc":
                fix = "UC";
                break;
            case "LC":
            case "lc":
                fix = "LC";
                break;
            default:
                fix = "error";
        }
        break;
    default:
        fix = "length";
}

答案 3 :(得分:0)

您可以使用以下内容:

 if(result.length <= 2)
    {
        switch(result[0])
        {
            case "UC":
                fix = "UC";
                break;
            case "uc":
                fix = "uc";
                break;
            case "UC":
                 fix = "LC";
                 break;
            case "uc":
                 fix = "lc";
                 break;
            default:
                  fix = "error";
       }
 }
 else
 {
     fix = "length";
 }