[英]How to change if-else statement to switch case statement in java
我的問題是如何將 if-else 語句更改為 switch 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";
像這樣嘗試
switch (result[0]) {
case "UC":
case "uc":
fix = "UC";
break;
case "LC":
case "lc":
fix = "LC";
break;
default:
fix = "error";
}
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";
另一種解決方案:
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";
}
您可以使用以下內容:
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.