1
  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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Ab Negusu
  • 11
  • 1

2 Answers2

2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • public class Math { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); double k = stdIn.nextDouble(); System.out.println(Math.pow(3-k/4,2)); } } – Ab Negusu Mar 05 '15 at 02:24
  • So I put that in but the pow part came up as an error...Did I do something wrong.? – Ab Negusu Mar 05 '15 at 02:24
  • You called your class `Math`, so you couldn't find `java.lang.Math.pow()`. Call your class something else. – user207421 Mar 05 '15 at 04:27
-1

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

alainlompo
  • 4,414
  • 4
  • 32
  • 41
  • If he was having difficulty parsing it, this wouldn't answer the question. But he is asking something else. – user207421 Mar 05 '15 at 04:29
  • Ya! his own Math class has hidden the access to java's – alainlompo Mar 05 '15 at 04:38
  • I changed it but I am still coming up with an error.. public class testExpression { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); double k = stdIn.nextDouble(); System.out.println(Math.pow("3-k = " / (4)^2)); } } – Ab Negusu Mar 05 '15 at 04:50
  • @AbNegusu Don't post comments under this pointless answer, and 'coming up with an error' isn't a problem description. But where did you get the quotes from? – user207421 Mar 05 '15 at 05:14
  • @Ab Negusu. What are you trying to do exactly? Are you trying to learn how to write mathematical expressions in Java, or do you have a further goal? – alainlompo Mar 05 '15 at 09:27