Sk4llsRPG
Sk4llsRPG

Reputation: 259

Java String to complete mathematical sum

In java, I am currently in the process of trying to find a way to do mathematical sums by typing in text to a JTextField, putting it into a String, and converting it to an int and solving. The problem is however, I don't want to simply put a number into the string but an actual sum including addition, subtraction etc.

Currently it will accept just doing something like, 1 which will go from string and convert to an int, but when I do '1+1' or even just '1+' it throws exceptions everywhere because '+' isn't a number.
Which I already understand that it wont work because int's only allow numbers.

Is there a way I can safely type a complete sum into the text field and convert it to an int somehow? Like typing 7-2*5 and then the answer being held in an int?

Thanks.

Upvotes: 0

Views: 832

Answers (3)

Zach
Zach

Reputation: 4792

You can use the JavaScript engine:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String expression = textField.getText();
System.out.println(engine.eval(expression));

Edit to allow all equations:

All you have to do now to allow things like sin, cos, tan is this:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String expression = textField.getText();

// Between here...
        expression = expression.
                replace("sin", "Math.sin").
                replace("cos", "Math.cos").
                replace("tan", "Math.tan").
                replace("sqrt", "Math.sqrt").
                replace("log", "Math.log").
                replace("pi", "Math.PI");
// And so on...

System.out.println(engine.eval(foo));

So then you can do something like:

5 + 5 - 2 / 5 + sin(55) - log(20)

Anything you want.

Upvotes: 2

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1530

This will do it for you.

  import javax.script.ScriptEngineManager;
    import javax.script.ScriptEngine;

    public class Test {
      public static void main(String[] args) throws Exception{
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        String foo = "40+2";//any mathematical operations +,-,*,/ 
        System.out.println(engine.eval(foo));
        } 
    }

Here you can put the methods describing the log/cos etc functions

String st = "10+3";
int result;
for(int i=0;i<st.length();i++)
{
  if(st.charAt(i)=='+')
  {
    result=Integer.parseInt(st.substring(0, i))+Integer.parseInt(st.substring(i+1, st.length()));
    System.out.print(result);
  }         
}

Upvotes: 2

Ole Harley
Ole Harley

Reputation: 21

See to java.util.regex.Matcher or java.util.regex.Pattern For ex:

import java.util.regex.Matcher; import java.util.regex.Pattern;

public class IpDnsValidateUtils {
    public static final int MAX_DNS_LEN = 39;
    private static final Pattern ptrnIp = Pattern
        .compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"); 
    private static final Pattern ptrnDomainName = Pattern
        .compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])){0,}[.][a-zA-Z]{2,5}$"); 

    public static boolean isValidIp(String value, boolean emptyTrue) {  boolean ret = false;    if (!value.isEmpty() || !emptyTrue) {
        Matcher m = ptrnIp.matcher(value);
        ret = m.matches();  } else {
        ret = true;     }   return ret;
    }

    public static boolean isValidDns(String value, boolean emptyTrue) {     boolean ret = false;    if (!value.isEmpty() || !emptyTrue) {
        Matcher m = ptrnDomainName.matcher(value);
        ret = m.matches();  } else {
        ret = true;     }   return ret;
    } }

or StringTokenizer class

Upvotes: 0

Related Questions