我想将以下if-else循环转换为Switch情况,我希望转换布尔条件。
public String getRandomValues(WebElement input) {
String value;
if (input.getAttribute("id").equalsIgnoreCase("FIRSTNAME")) {
value = "User";
} else if (input.getAttribute("id").equalsIgnoreCase("LASTNAME")) {
value = "Name";
} else if (input.getAttribute("id").equalsIgnoreCase("ACCOUNTNUMBER")) {
value = "0123945486855";
} else if (input.getAttribute("id").equalsIgnoreCase("EMAIL")) {
value = "user@domain.com";
} else if (input.getAttribute("id").equalsIgnoreCase("PHONE")) {
value = "98287825858";
} else if (input.getAttribute("id").equalsIgnoreCase("DATE")) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
value = dateFormat.format(new Date());
} else {
value = "Random Value 123";
}
return value;
}
有人可以帮忙吗?
答案 0 :(得分:5)
你可以这样做:
String id = input.getAttribute("id").toUpperCase();
switch(id) {
case "FIRSTNAME":
// something
break;
.....
}
答案 1 :(得分:1)
Switch接受String
作为参数,因此你可以这样做:
switch (input.getAttribute("id").toUpperCase())
{
case "FIRSTNAME":
value = "User";
break;
case "LASTNAME":
value = "Name";
break;
//and so on
case "DATE":
{
// You need braces to declare a local variable in a case
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
value = dateFormat.format(new Date());
break;
}
default: // the same as your 'else'
value = "Random Value 123";
}
答案 2 :(得分:0)
public String getRandomValues(WebElement input) {
String inputValue = input.getAttribute("id").toUpperCase();
switch (inputValue) {
case "FIRSTNAME":
return "User";
case "LASTNAME":
return "Name";
case "ACCOUNTNUMBER":
return "0123945486855";
case "EMAIL":
return "user@domain.com";
case "PHONE":
return "98287825858";
case "DATE":
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
return dateFormat.format(new Date());
default:
return "Random Value 123";
}
}