-1

I am a bit stuck on how I would execute a statement such as "5 + 10 * 2 / 5". I'm new to JAVA and have not the slightest on how to go about it. any ideas?

I need to write a method that takes the expression in parameters. eval("6*3+2"); So it has to take them in as a string and convert them to a double

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Clay Banks
  • 4,483
  • 15
  • 71
  • 143
  • You can write `int result = 5 + 10 * 2 / 5` but that answer does not help you much, does it? What do you really want to do? – Thilo May 23 '13 at 02:07

2 Answers2

0

If we can assume each token is space delimited and it is a non-Polish notation this will be sufficient:

Queue<Integer> numerals = new Queue<Integer>();
Queue<String> operators = new Queue<String>();
String[] tokens = input.split(" ");    
int numeralIndex = 0;
for(String token:tokens)  
{
      if(numeralIndex %2 == 0)
      {
           numerals.enqueue(Integer.parseInt(token));  
      } else{  
           operators.enqueue(token);
      }  
      numeralIndex++;  
}    

Now that you have the tokens in order you need to remove them from the queues to reassemble your initial calculation. You will also need the list of symbols so that you can correctly bind the statements:

int runningTotal = 0;
if(operator.equals("+")  
{  
       runningTotal += (previous+current);  
}else if(operator.equals("-")  
{  
       runningTotal-=(previous-current);
}      //etc

I will leave the rest as an exercise for your homework assignment.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
-3

did not get what you want exactly, but try this

int result = 0;

int val_a=5;

int val_b=10;

int val_c=2;

now to print the result;

int result = (your calculation here);

systm.out.println("result = "+result);

  • His question states _it has to take them in as a string and convert them to a double_. – Sotirios Delimanolis May 23 '13 at 02:41
  • so the easiest way is :- String value_str= "5"; double val_a= Double.parseDouble(your string value); value should me only containing numbers – user3674938 May 23 '13 at 08:56
  • sory i got i wrng. i have to check your string one by one, then if you got a number asign it into a double variable.. like that you have to get the all numbers while you asigning it to a double value and executing the condition ----- > for (int i = 0;i < str.length(); i++){ System.out.println(str.charAt(i)); } <-------- – user3674938 May 23 '13 at 09:15