简体   繁体   中英

Someone please explain this to me

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM