39656

Add numbers with the word “add”

Question:

I am writing to offer an application in Java right now and instead of using the operator "+", the user of the application can literally use the word "add" to add two numbers together.

I'm quite stuck on how to do this because I can't really use a method in order to complete the function considering I'd have to type "add()" rather than just "add". Unless there is a way to execute a method without the parentheses. Would I have to write a completely new class or is there an easier way to do this?

Answer1:

(An expansion on the idea presented by user710502)

You can use <a href="http://java.sun.com/developer/technicalArticles/ALT/Reflection/" rel="nofollow">reflection</a>.

double a = Double.parseDouble(some user input); double b = Double.parseDouble(some user input); String operation = some user input; // i.e. "add", "subtract" Method operator = Calculations.class.getMethod(operation, double.class, double.class); // NoSuchMethodException is thrown if method of operation name isn't found double result = (Double) operator.invoke(null, a, b);

In some sort of calculations class:

public static double add(double a, double b) { return a + b; } public static double subtract(double a, double b) { return a - b; } // and so forth

Answer2:

Just a little explanation on what you could do based on what the user enters:

int x = get it from the user; int y = get it from the user; string operation = get it from the user; <ul><li>Create separate methods for the operations (i.e add(int x, int y), multiply(int x, int y), etc..)</li> </ul>

Then create a method thag gets the values (x, y, string) say.. you can call it calculate(int x, int y, string operation)

Then in the calculuate method have a switch statement:

switch(operation) { case "add": add(x,y); break; case "multiply": multiply(x,y); break; etc... }

Well, got you something to think about :).

Answer3:

There's no way to do this in Java. You have two options:

1)Use a preprocessor. 2)Write it in a different language. You can write things in other languages and still have it compatible with Java classes and libraries.

Answer4:

The consensus in comments seems to be 'Why would you want to do this? It is slow and cumbersome'. While the latter part is true, it is commonly done. See <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html" rel="nofollow">ScriptEngine</a> as an example. Here is a demo of the <a href="http://www.pscode.org/jse.html" rel="nofollow">JavaScript ScriptEngine</a> in an applet.

The reader might note that ScriptEngine is an interface, suggesting an answer of 'implement your own script engine, based on the rules required'. Whether or not it is a good idea to create another scripting language, is left as an exercise for the reader.

Recommend

  • In C#, how do I add event handlers to an object based on names?
  • How to create c# console application to cosume the .net webservice [closed]
  • Get MethodInfo for any method with any signature (delegate for any signature)
  • Get form values in Symfony2 controller , Child does not exist
  • Android get Serial Number
  • Matlab code optimization and removing loops [closed]
  • Ordering of eigenvectors when calculating eigenvectors using LAPACK's ssteqr
  • Tkinter: Determine Widget Position relative to Root Window
  • ASP.NET 5: Error with Nuget package in Class library Package
  • GMP Bit shift doesn't work on negative numbers
  • MVC - Dynamically loading Partial Views
  • Timer once a minute on the minute
  • how to use asyncio with boost.python?
  • Finding the number of elements less than or equal to k in a multiset
  • How to develop MS CRM kind of application
  • How to use the resource module to measure the running time of a function?
  • Refactoring advice: maps to POJOs
  • What is the default HTTP verb in WebApi ? GET or POST?
  • Translating C# to PowerShell in InterIMAP
  • Detecting null parameter in preprocessor macro
  • TFS 2015 - Waiting for an agent to be requested
  • How to synchronize jQuery dialog box to act like alert() of Javascript
  • Android Activity.onWindowFocusChanged doesn't get called from within TabHost
  • Object and struct member access and address offset calculation
  • How do I open a C file with a relative path?
  • Use of this Javascript
  • Linq Objects Group By & Sum
  • Spring security and special characters
  • Trying to switch camera back to front but getting exception
  • How to set my toolbar fixed while scrolling android
  • AT Commands to Send SMS not working in Windows 8.1
  • php design question - will a Helper help here?
  • How to format a variable of double type
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Buffer size for converting unsigned long to string
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • apache spark aggregate function using min value
  • Programmatically clearing map cache
  • Sorting a 2D array using the second column C++