简体   繁体   中英

using OR in an argument to a method

How can I include multiple terms as a single arguments to a method?

For example: method is declared as follows:

 public void showSchedules(String day, String AMPM);

I want to call something like

showSchedules ("Monday" || "Tuesday", AM);

but the operators cannot be applied to java lang String. Any tips?

What you are suggesting is not possible. The || operator in Java is a logical (boolean) operator. It evaluates the boolean expressions on either side (if necessary) and returns a boolean value. So your suggestion will never work since the expressions on each side are Strings and not booleans.

You have three options here:

  1. Pass each argument individually into the method, or if you don't know how many there will be pass them in an array or some other collection.
showSchedules("Monday", "Tuesday", AM) {...}

or

showSchedules(new String[] {"Monday", "Tuesday"}, AM) {...}
  1. Call the method twice, passing in one argument each time and then deal with the results in the calling method.

  2. Invert the order of params and use varargs :

showSchedules(String AmPm, String... days) {...}

No. You cannot do that in passing arguments. However you can only control the functionality.

For ex

public void showSchedules(String day, String AMPM) {
    if (day.equals("Monday") ||  day.equals("Tuesday") ) {
       //TODO
    }

  }

You can totally do that with an varargs, like so:

day will be an array of strings and you can pass as many as you want

public void showSchedules(String AMPM, String... day) {
    // you'll have to iterate through them here
    for(String d:day)
{
  switch(d)
    {
        case "Monday":
        break;
        case "Tuesday":
        break;
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM