2

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

Can anyone help ?

Happy Bird
  • 902
  • 1
  • 9
  • 27
Sameer Patil
  • 433
  • 3
  • 9

3 Answers3

5

You can do this:

String id = input.getAttribute("id").toUpperCase();
switch(id) {
    case "FIRSTNAME": 
        // something
        break;
    .....
}
Gurwinder Singh
  • 37,207
  • 6
  • 50
  • 70
1

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";
}
Michael
  • 37,794
  • 9
  • 70
  • 113
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";
        }
    }