lemmi lemmi - 1 year ago 44
Java Question

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) {...}


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) {...}