Re: Passing "<", ">", "=", etc as an argument to a method?

From: Anthony Borla (ajborla_at_bigpond.com)
Date: 11/28/03


Date: Fri, 28 Nov 2003 01:37:16 GMT


"Eric A. Forgy" <forgy@uiuc.edu> wrote in message
news:3fa8470f.0311271719.71a50987@posting.google.com...
> Hello,
>
> I am just learning Java and am trying to write a method
> that does something like
>
> //===========================================
> public Static List find(double[] array,double val,String relationalOp)
> {
>
> List list = new ArrayList();
> for (int m = 0;m < array.length;m++) {
> // The following line is the problem
> if (array[m] relationalOp val) {
> list.add(array[m]);
> }
> }
> return list;
> }
> //===========================================
>
> Is it possible to use an argument directly in an if statement
> like that?
>

No, it is not possible in languages like Java, C++, or C#, but it *is*
possible in some scripting languages.

>
> I am trying to avoid having to rewrite the same method
> over and over again, once for each relational
>operator "==", "<", ">", "<=", ">=", not to mention all
> of their "not" versions.
>
> What is the best way to do this?
>

You need to map each operator string to a method that performs the required
task, and to which you also pass the required arguments [or, in this case,
operands]. You can design a solution varying in complexity and
sophistication; probably the very simplest is something like:

     if (relationalOp.equals("<"))
        doLessThan(value1, value2)
    else if (relationalOp.equals("="))
        doEquals(value1, value2)
    ...

You get the picture, I'm sure.

I hope this helps.

Anthony Borla



Relevant Pages

  • Desining Classes
    ... I am learning Java and am getting to grips with the language and class ... libraries well. ... design sets of classes for my own programs. ...
    (comp.lang.java.help)
  • Re: Elbow Pads?
    ... I sure hope their products are better than their website, ... great example of how not to design a site. ... what's the point of learning Java and Flash if you never ...
    (rec.boats.paddle)