简体   繁体   English

在方法的参数中使用OR

[英]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: 例如:method声明如下:

 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. 但是运算符不能应用于java lang String。 Any tips? 有小费吗?

What you are suggesting is not possible. 您的建议是不可能的。 The || || operator in Java is a logical (boolean) operator. Java中的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 : 反转参数的顺序并使用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: 您可以使用varargs完全做到这一点,如下所示:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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