Como Somar Números com a exp4j

Simples

import static java.lang.System.out;

import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;

public final class Exp4jSample {

  public static void main(final String[] args) throws Exception {
    final Calculable calc = new ExpressionBuilder("1 + 1").build();

    out.println(calc.calculate()); // imprime "2.0"
  }

}

Com withVariable

import static java.lang.System.out;

import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;

public final class Exp4jSample {

  public static void main(final String[] args) throws Exception {
    final Calculable calc = new ExpressionBuilder("x + y").withVariable("x", 1d).withVariable("y", 1d).build();

    out.println(calc.calculate()); // imprime "2.0"
  }

}

Com withVariableNames

import static java.lang.System.out;

import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;

public final class Exp4jSample {

  public static void main(final String[] args) throws Exception {
    final Calculable calc = new ExpressionBuilder("x + y").withVariableNames("x", "y").build();

    out.println(calc.calculate(1d, 1d)); // imprime "2.0"
  }

}

Com withVariables

import static java.lang.System.out;

import java.util.HashMap;
import java.util.Map;

import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;

public final class Exp4jSample {

  public static void main(final String[] args) throws Exception {
    final Map<String, Double> varMap = new HashMap<String, Double>();

    varMap.put("x", 1d);
    varMap.put("y", 1d);

    final Calculable calc = new ExpressionBuilder("x + y").withVariables(varMap).build();

    out.println(calc.calculate()); // imprime "2.0"
  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s