1

In relatively new to java though i have been programming for sometime now. i figure doing a fun math project for my daughter to help her learn math would be an easy way to test what java is capable of. So in effort to try and learn efficient ways of doing programming, Is there a way to convert a string or character value from (/,,-,+) to an operator /-+?

example:

 string/char  textin = ""
 text = JOptionPane "input box"   ("*")
 int results = 0
 int num1 = 9
 int num2 = 5

 public static void calc(int num1,int num2, string/char textin)
 {
  results = num1 "some method"(textin) num2         // convert "*" to *
 }

The purpose of this question is to reduce the amount of calculations needed to due all four operators. To use one generic method to do all four operators. Is this possible?

Kyle5385
  • 11
  • 1
  • 4
    searching the web is your friend: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Tom Freudenberg Oct 31 '15 at 23:54

1 Answers1

6

No, that's not possible. The closest you can come is define a helper method that interprets the string as an operator and applies it.

public static double operate(double x, double y, String operator) {
    switch(operator) {
         case "*":
             return x*y;
         case "/":
             return x/y;
         // etc.
         default:
             throw IllegalArgumentException("Unknown operator");
    }
} 
wvdz
  • 16,251
  • 4
  • 53
  • 90