473,835 Members | 1,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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?

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?

Thank you for any help.

Eric
Jul 17 '05 #1
5 2802

"Eric A. Forgy" <fo***@uiuc.edu > wrote in message
news:3f******** *************** ***@posting.goo gle.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.e quals("<"))
doLessThan(valu e1, value2)
else if (relationalOp.e quals("="))
doEquals(value1 , value2)
...

You get the picture, I'm sure.

I hope this helps.

Anthony Borla

Jul 17 '05 #2
While it was 28/11/03 1:37 am throughout the UK, Anthony Borla sprinkled
little black dots on a white screen, and they fell thus:

<snip>
if (relationalOp.e quals("<"))
doLessThan(valu e1, value2)
else if (relationalOp.e quals("="))
doEquals(value1 , value2)
...


Why not make relationalOp a number, and save the overhead of doing
string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.

Stewart.

--
My e-mail is valid but not my primary mailbox, aside from its being the
unfortunate victim of intensive mail-bombing at the moment. Please keep
replies on the 'group where everyone may benefit.
Jul 17 '05 #3

"Stewart Gordon" <sm*******@yaho o.com> wrote in message
news:bq******** **@sun-cc204.lut.ac.uk ...
While it was 28/11/03 1:37 am throughout the UK, Anthony
Borla sprinkled little black dots on a white screen, and they
fell thus:

<snip>
if (relationalOp.e quals("<"))
doLessThan(valu e1, value2)
else if (relationalOp.e quals("="))
doEquals(value1 , value2)
...


Why not make relationalOp a number, and save the overhead
of doing string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.


Indeed, I fully agree ! However, my response was tailored to the OP's code:
'relationalOp' was a 'String' type.

I *did*, however, mention that:

'You can design a solution varying in complexity and
sophistication. ..'

and your solution is, most certainly, in this latter group :) !

Cheers,

Anthony Borla
Jul 17 '05 #4
Stewart Gordon wrote:
While it was 28/11/03 1:37 am throughout the UK, Anthony Borla sprinkled
little black dots on a white screen, and they fell thus:

<snip>
if (relationalOp.e quals("<"))
doLessThan(valu e1, value2)
else if (relationalOp.e quals("="))
doEquals(value1 , value2)
...

Why not make relationalOp a number, and save the overhead of doing
string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.


Even better: use polymorphism. E.g.

// WARNING: Uncompiled, untested code
public class Helper
{
public static final Finder EQUALS = new EqualsFinder();
public static final Finder GREATER_THAN = new GreaterThanFind er();
// etc.

public static List find(double[] array, double val, Finder finder)
{
List result = new ArrayList();
for (int i = 0; i < array.length; i++)
{
if (finder.satisfi es(array[i], val))
{
result.add(new Double(array[i]));
}
}
}

public static interface Finder
{
public boolean satisfies(doubl e candidate, double val);
}

public static class EqualsFinder
{
public boolean satisfies(doubl e candidate, double val)
{
return (candidate == value);
}
}

public static class GreaterThanFind er
{
public boolean satisfies(doubl e candidate, double val)
{
return (candidate > value);
}
}

}

Ray

Jul 17 '05 #5

Hi Eric,
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)


It's a good example method. Unfortunately, Java is not very good at
handling such cases, because it does not treat methods (or operations)
as normal values. You cannot directly pass a method as an argument to
another method.

The closest you could get would be to use anonymous classes as a
substitute, as in the following (beware, very verbose)!

import java.util.*;

public class Main {

abstract static class DoubleOp
{
abstract boolean test(double x, double y);
}

public static List find(double[] array,double val, DoubleOp op){
List list = new ArrayList();
for (int m = 0;m < array.length;m+ +) {
// The following line is the problem
if (op.test(array[m], val)) {
list.add(new Double(array[m]));
}
}
return list;
}

public static void main(String[] args) {
double[] numbers = new double[]{ -10, -1, 0, 2, 5, 11 };

DoubleOp leq = new DoubleOp() {
boolean test(double x, double y) {
return x < y;
}
};
List negative = find(numbers, 0, leq);
System.out.prin tln("Negative numbers: " + negative);

DoubleOp neq = new DoubleOp() {
boolean test(double x, double y) {
return x != y;
}
};
List nonZero = find(numbers, 0, neq);
System.out.prin tln("Non-zero numbers: " + nonZero);
}
}
It is much easier if you can use a language that support methods as
values. For instance, here is the same code in the Nice language, which
is an extension of Java with many features, including method values (I
am one of the developers of Nice. You can find more about it at
http://nice.sf.net)

List<double> find(double[] array,double val,(double,dou ble)->boolean op)
{
List<double> list = new ArrayList();
for (int m = 0;m < array.length;m+ +) {
// The following line was the problem
if (op(array[m], val)) {
list.add(array[m]);
}
}
return list;
}

void main(String[] args)
{
double[] numbers = [ -10, -1, 0, 2, 5, 11 ];

let negative = find(numbers, 0, (double x,double y)=> x < y);
System.out.prin tln("Negative numbers: " negative);

let nonZero = find(numbers, 0, (double x,double y)=> x != y);
System.out.prin tln("Non-zero numbers: " nonZero);
}
Some comments:

(double,double)->boolean
This is the type of a method, which has two arguments of type
double, and returns a boolean.

let negative =
This is a way to declare a local variable, letting the compiler
find what is its type.

(double x,double y)=> x < y
This is an expression that represents the '<' comparison on doubles.
One way to generalize your method find is to give it only two arguments:
the array of number, and a method with _one_ argument of type double,
returning a boolean to say if that number should be included in the
results. This generalization is what we call 'filter'. So this code
could be simply rewritten as:

void main(String[] args)
{
double[] numbers = [ -10, -1, 0, 2, 5, 11 ];

let negative = filter(numbers, (double x)=> x < 0);
System.out.prin tln("Negative numbers: " negative);

let nonZero = filter(numbers, (double x)=> x != 0);
System.out.prin tln("Non-zero numbers: " nonZero);
}
Enjoy!

Daniel

The Nice programming language: http://nice.sf.net

Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5038
by: Son KwonNam | last post by:
When I try <xsl:value-of select="count('/GROUPS/GROUP')"/> on JSTL <x:transform> tag, I got the following error message. org.apache.jasper.JasperException: Can not convert #STRING to a NodeList! but, if I try that on Sonic XIS XSL transform API It works fine. What's the problem? Java(apache JSTL) does not support XPath functions?
1
6836
by: Christian Schmidbauer | last post by:
Hello! I prepare my XML document like this way: ------------------------------------------------------- PrintWriter writer; Document domDocument; Element domElement; // Root tag
7
2094
by: Diandian Zhang | last post by:
Does anyone have an idea, how to do it? Thanks in advance!
22
3355
by: Dr Duck | last post by:
GDay all, Something seems odd to me.... I wrote a simple C# function public void bind(ref object a, ref object b, bool atob) { if(atob) b = a; else
3
2485
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going wrong? I am using g++ (GCC) 3.3.5 on a Debian Sarge system. The compiler complains: //**************************** //**************************** Compiler output starts *********** cd /home/red/tmp/testprogs/
10
3436
by: Blue® | last post by:
I would like to call the content of content.htm (containing only HTML codes) into index.htm. This is usually done by renaming index.htm to index.shtml and use this tag: <!--#include file="content.htm" --> But I do not want to use SSI. Is it possible to call it using something like:
2
6868
by: andrew007 | last post by:
I do xml / xslt transformation using asp.net but I found any value (w/xml format) in xml node html-encoded to &lt and &gt format if it's > or < tag. Since I have sub xml data in a parent xml node as a value. Check out the following problem. I want to convert the value in <WpDatesXml> node to have a valid "<" and ">" instead of &lt or &gt format so that I can use this xml for another use. Please help! <NewDataSet> <Table1>
2
2020
by: Peter Laman | last post by:
In my app I need to dynamically generate a series hyperlinks. Each hyperlink's action must be to focus a field in a <form>. I created the following function to create such a link (the argument is a field object, e.g. <input>): function createFieldAnchor(field, linkText) { var anchor = document.createElement("a"); anchor.field = field; anchor.href='javascript:this.focusField()';
0
9808
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9652
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10523
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10561
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9346
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6966
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5638
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5804
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3089
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.