-5

Someone please help, How exactly can I take a string and break it up evenly.

for example (41-25) how can I pull the 41 or 25 out instead of getting a seperate 4 and 1. Whenever I enter a double it registers it as each single digit including the period but not as a whole.

static double evaluate(String expr){
  //Add code below
  Stack<String> operators = new Stack<String>();
  Stack<Double> values = new Stack<Double>();
  String[] temp = expr.split("");
  Double value = 0.0;

  for(int i=0; i< temp.length;i++){

   if(temp[i].equals("(")) continue;
   else if(temp[i].equals("+")) operators.push(temp[i]);
   else if(temp[i].equals("-")) operators.push(temp[i]);
   else if(temp[i].equals("*")) operators.push(temp[i]);
   else if(temp[i].equals("/")) operators.push(temp[i]);
   else if(temp[i].equals(")")) {
     String ops = operators.pop();
     value = values.pop();
     value = operate(values.pop(), value, ops);
     System.out.println(value);
     values.push(value);
   }
   else{
      System.out.println(temp[i]);
      Double current = Double.parseDouble(temp[i]);
      values.push(current);
  }


}
return 0;
}
jeprubio
  • 17,312
  • 5
  • 45
  • 56
  • 2
    Rather than split the expression by characters, split it on the operator (e.g. ```+```) Alternatively, use regex (although that may be a bit advanced) – Michael Bianconi Mar 10 '20 at 18:40
  • 2
    What do you mean by "evenly"? Like get the number as a whole? – MT756 Mar 10 '20 at 18:40
  • i need to solve this stringi cant just take out the operators – luistinoco Mar 10 '20 at 18:57
  • Possibly related: [How to evaluate a math expression given in string form?](https://stackoverflow.com/q/3422673), especially [this answer](https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form/26227947#26227947) – Pshemo Mar 10 '20 at 19:27

1 Answers1

0

I would split the string before and after any operator rather than splitting every character:

static double evaluate(String expr){
  //Add code below
  ...
  String[] temp = expr.split("((?<=[\+\-\*\/])|(?=[\+\-\*\/]))");  // Changes "41-25" to ["41", "-", "25"]

This uses regex to split the string using a positive look behind (?<=) and a positive lookahead (?=) with a character set inside for the four operators that you need [\+\-\*\/] (the operators are escaped with a backslash.

Any string will split before and after any operator. If you need more operators, they can be added to the character set.

With Java you could even make your character set a String to remove duplicate code by putting:

String operators = "\\+-\\*/";

String[] temp = expr.split("((?<=[" + operators + "])|(?=[" + operators + "]))";

This method enables you to change what operators to split on easily.

user11809641
  • 815
  • 1
  • 11
  • 22