Learn, Share, Build

October 09, 2017, at 09:07 AM

I'm trying to define a class Expression, which can represent any mathematical expression as its name suggests. It takes a String and uses its information to store the expression in its fields.

So its constructor should look like this:

        public Expression(String expr)

When I make an instance of this class, I want to be able give its constructor any type of variables or sequence thereof and make the constructor convert it into a String. For example, I want to be able to write:

Expression e1 = new Expression(aNumber*x + anInt*y) 

instead of

Expression e1 = new Expression("" + aNumber+"*x+" + anInt+"*y+")

where x and y are not declared or initialised variables, but symbols to be converted into the String (aNumber and anInt are declared and initialised.)

So my question is: Can I automate the process of concatenating Numbers and Strings in the constructor into an easily usable one, as shown above?

Thanks in advance!

Answer 1

You have to actually implement it, something like:

public class Expression {
    private final String expr;
    public Expression(Object... args){
        this.expr = Arrays.asList(args).stream().map(Object::toString).collect(Collectors.joining());
    public String getExpr() {
        return expr;

And then:

new Expression(aNumber, "*x + ", anInt, "*y");
Rent Charter Buses Company
Learn, Share, Build

Learn, Share, Build

I would like to create a calculator in JavaI have some problem implementing the simplify method

Learn, Share, Build

Learn, Share, Build

I'm working on a java program that should accept input from a file into an arraylist and linkedlist and convert them to strings to read the expression and convert it from infix to postfix notation, and evaluate the outputI'm stuck at conversion of array/linked...

Learn, Share, Build

Learn, Share, Build


Learn, Share, Build

Learn, Share, Build

I need to call AWS API Gateway endpoint and I can do it from java 8 but from java 6 the same code throws exception: javaxnet