如果else具有布尔条件,如何将其转换为switch?

kmpatx3s  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(412)

我想把下面的if-else循环转换成switch case,在这里我想转换布尔条件。

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;
    }

有人能帮忙吗?

tyu7yeag

tyu7yeag1#

您可以这样做:

String id = input.getAttribute("id").toUpperCase();
switch(id) {
    case "FIRSTNAME": 
        // something
        break;
    .....
}
ncgqoxb0

ncgqoxb02#

交换机接受 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";
}
u2nhd7ah

u2nhd7ah3#

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";
        }
    }

相关问题