Ab Negusu
Ab Negusu

Reputation: 5

Turning math expressions into Java code

  1. (3-k /4 )^2

  2. 9x-(4.5+y)/2x

How do I go about translating them into Java code expressions? My book examples are not helping as much.

Upvotes: -2

Views: 821

Answers (2)

alainlompo
alainlompo

Reputation: 4434

One simple way is to parse it recursively in regard to the operators.

A mathematic expression like 9x-(4.5+y)/2x is made of three parts: operand1 operator operand2 where operand1 itself is a mathematical expression and operand2 is also a mathematical expression

In parsing it you should consider also operators priorities

Upvotes: -1

user207421
user207421

Reputation: 311050

Most of it already is a Java expression. The only parts that aren't are:

  1. The ^ operator, by which you presumably mean exponentiation. Any written expression of the form xy is expressed in Java as

    Math.pow(x, y)
    
  2. The elision of multiplication operators. 2x is expressed in Java (and all other programming languages I've ever used except assembler) as 2*x.

Upvotes: 2

Related Questions