Sanlover

Untitled

Dec 1st, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. private static String getFixed(String expr) throws Exception {
  2. String result = expr.replaceAll("\\b" + "\\(" + "\\b", "*(");
  3. result = result.replaceAll("\\b" + "\\)" + "\\b", ")*");
  4.  
  5. while(true){
  6. boolean isChanged = false;
  7. for(int i = 0 ; i < result.length() && !isChanged;i++){
  8. char symbol = result.charAt(i);
  9. if(symbol == '-' || symbol == '+' || symbol == '*' || symbol == '/'){
  10. boolean isFound = true;
  11. for(int j = i-1 ; j>= 0; j--){
  12. if(result.charAt(j) == '('){
  13. break;
  14. }
  15. if(result.charAt(j) >= '0' && result.charAt(j) <= '9' || result.charAt(j) == ')' ){
  16. isFound = false;
  17. }
  18. }
  19. if(isFound){
  20. if(symbol == '-' || symbol == '+'){
  21. result = result.substring(0,i) + "0" + result.substring(i);
  22. } else {
  23. throw new Exception("Operator on " + i + " position does not have any variable on left side");
  24. }
  25. isChanged = true;
  26. }
  27. }
  28. }
  29. if (!isChanged) {
  30. break;
  31. }
  32. }
  33. return result;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment