Reputation: 461
I want to convert following if-else loop into Switch case where i want Boolean conditions to be converted.
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 = "[email protected]";
} 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;
}
Can anyone help ?
Upvotes: 2
Views: 156
Reputation: 39467
You can do this:
String id = input.getAttribute("id").toUpperCase();
switch(id) {
case "FIRSTNAME":
// something
break;
.....
}
Upvotes: 5
Reputation: 31
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 "[email protected]";
case "PHONE":
return "98287825858";
case "DATE":
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
return dateFormat.format(new Date());
default:
return "Random Value 123";
}
}
Upvotes: 0
Reputation: 44110
Switch accepts a String
as a parameter, so you could do:
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";
}
Upvotes: 1