基于Java的表达式求解算法

guz6ccqo  于 2024-01-05  发布在  Java
关注(0)|答案(3)|浏览(195)

我试图创建一个程序,将在一个表达式作为一个字符串,并解决它。所以,如果输入是3 + 5,它将返回8。我已经做了大部分的编码,但我不知道为什么我一直得到一个UncertedOperationExpression在Java中。请帮助,如果你可以!

**我还必须在这个作业中使用ArrayLists,因为我还没有学习列表。这是我目前为止的代码:

  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.ArrayList;
  4. public class FirstPart {
  5. public static void main(String[] args) {
  6. String sampleString = "1 + 2 + 3 / 2 + 1";
  7. String[] items = sampleString.split(" ");
  8. List<String> itemList = Arrays.asList(items);
  9. System.out.println(itemList);
  10. for(int zz=0; zz<itemList.size(); zz++)
  11. if(itemList.get(zz).equals("*"))
  12. {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))*Integer.parseInt(itemList.get(zz+1)))));
  13. itemList.remove(zz+1);
  14. itemList.remove(zz);
  15. zz--;}
  16. else if(itemList.get(zz).equals("/"))
  17. {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))/Integer.parseInt(itemList.get(zz+1)))));
  18. itemList.remove(zz+1);
  19. itemList.remove(zz);
  20. zz--;}
  21. for(int zz=0; zz<itemList.size(); zz++)
  22. if(itemList.get(zz).equals("+"))
  23. {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))+Integer.parseInt(itemList.get(zz+1)))));
  24. itemList.remove(zz+1);
  25. itemList.remove(zz);
  26. zz--;}
  27. else if(itemList.get(zz).equals("-"))
  28. {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))+Integer.parseInt(itemList.get(zz+1)))));
  29. itemList.remove(zz+1);
  30. itemList.remove(zz);
  31. zz--;}
  32. System.out.println(itemList);
  33. }
  34. }

字符串
再次感谢如果你能帮助!

332nm8kg

332nm8kg1#

如果从这样的数组构造List

  1. List<String> itemList = Arrays.asList(items)

字符串
返回的列表不允许从列表中删除项目

  1. itemList.remove(zz + 1); // throws java.lang.UnsupportedOperationException


相反,创建一个支持删除的空列表,并将所有数组元素添加到其中:

  1. List<String> itemList = new java.util.ArrayList<>();
  2. java.util.Collections.addAll(itemList, items);

展开查看全部
xjreopfe

xjreopfe2#

尝试阅读关于逆波兰符号算法。它似乎做正是你需要的,你只需要实现它。
https://en.wikipedia.org/wiki/Reverse_Polish_notation

qfe3c7zg

qfe3c7zg3#

见我的java程序原件和由Rishi shakya类10日。一个非常强大的表达式求解器可以在BODMAS中轻松执行DMAS。//原件

  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3. public class Calculator {
  4. private String arithmeticExpression;
  5. private ArrayList<Double> numberList = new ArrayList<>();
  6. private ArrayList<Character> operatorList = new ArrayList<>();
  7. public Calculator(String ArithmeticExpression) {
  8. this.arithmeticExpression = '+' + ArithmeticExpression;
  9. }
  10. private static String getArithmeticExpression() {
  11. Scanner in = new Scanner(System.in);
  12. System.out.println("Enter Your ArithmeticExpression");
  13. return in.nextLine();
  14. }
  15. private double evaluate(double operand1, double operand2, char operator) {
  16. double result = 0;
  17. switch (operator) {
  18. case '+' -> result = operand1 + operand2;
  19. case '-' -> result = operand1 - operand2;
  20. case '*' -> result = operand1 * operand2;
  21. case '/' -> result = operand1 / operand2;
  22. }
  23. return result;
  24. }
  25. private void getNumbers() {
  26. String[] Numbers = this.arithmeticExpression.split("[+\\-*/]");
  27. for (String Number : Numbers) {
  28. try {
  29. numberList.add(Double.parseDouble(Number));
  30. } catch (NumberFormatException ignored) {
  31. }
  32. }
  33. }
  34. private void simplifyAdditionSubtractionOperators() {
  35. StringBuilder simplifiedArithmeticExpression = new StringBuilder();
  36. String operator = "";
  37. int lowerBound, upperBound, flowControl = 0, numberCounter = 0;
  38. char finalOperator, Character;
  39. for (int counter = 0; counter < this.arithmeticExpression.length(); counter++) {
  40. Character = this.arithmeticExpression.charAt(counter);
  41. finalOperator = Character;
  42. if (Character == '-' || Character == '+') {
  43. lowerBound = counter;
  44. for (upperBound = lowerBound + 1; upperBound < this.arithmeticExpression.length() &&
  45. (this.arithmeticExpression.charAt(upperBound) == '+' || this.arithmeticExpression.charAt(upperBound) == '-'); upperBound++) {
  46. if (this.arithmeticExpression.charAt(upperBound - 1) == '+' || this.arithmeticExpression.charAt(upperBound - 1) == '-')
  47. if (finalOperator == this.arithmeticExpression.charAt(upperBound))
  48. finalOperator = '+';
  49. else finalOperator = '-';
  50. }
  51. counter = upperBound - 1;
  52. }
  53. if (Character == '-' || Character == '+' || Character == '*' || Character == '/') {
  54. flowControl = 1;
  55. operator = String.valueOf(finalOperator);
  56. }
  57. if (operator.equals("-"))
  58. operator = "+-";
  59. if (flowControl == 1) {
  60. simplifiedArithmeticExpression.append(operator);
  61. flowControl = 2;
  62. } else if (flowControl == 2) {
  63. simplifiedArithmeticExpression.append(numberList.get(numberCounter));
  64. numberCounter++;
  65. flowControl = 0;
  66. }
  67. }
  68. this.arithmeticExpression = simplifiedArithmeticExpression.toString();
  69. }
  70. private void simplifyMultiplicationDivisionOperators() {
  71. char finalOperator, character;
  72. ArrayList<Character> simplifiedOperatorList = new ArrayList<>();
  73. for (int counter = 0; counter < this.arithmeticExpression.length(); counter++) {
  74. character = this.arithmeticExpression.charAt(counter);
  75. finalOperator = character;
  76. if (character == '/' || character == '*')
  77. if (this.arithmeticExpression.charAt(counter + 1) == '+')
  78. counter++;
  79. if (character == '-' || character == '+' || character == '*' || character == '/')
  80. simplifiedOperatorList.add(finalOperator);
  81. }
  82. operatorList = simplifiedOperatorList;
  83. }
  84. private void evaluateMultiplicationDivision() {
  85. char operator;
  86. double result;
  87. while (operatorList.contains('*') || operatorList.contains('/'))
  88. for (int i = 1; i < operatorList.size(); i++) {
  89. operator = operatorList.get(i);
  90. if (operator == '*' || operator == '/') {
  91. result = evaluate(numberList.get(i - 1), numberList.get(i), operator);
  92. operatorList.remove(i);
  93. numberList.remove(i);
  94. numberList.add(i, result);
  95. numberList.remove(i - 1);
  96. }
  97. roundAllNumbers(5);
  98. }
  99. }
  100. private void evaluateAdditionSubtraction() {
  101. double sum = 0;
  102. roundAllNumbers(5);
  103. for (double number : numberList)
  104. sum += number;
  105. numberList.clear();
  106. numberList.add(sum);
  107. roundAllNumbers(5);
  108. }
  109. private void getActualNumbers() {
  110. numberList.clear();
  111. String[] Numbers = this.arithmeticExpression.split("[+*/]");
  112. for (String Number : Numbers) {
  113. try {
  114. numberList.add(Double.parseDouble(Number));
  115. } catch (NumberFormatException ignored) {
  116. }
  117. }
  118. }
  119. private void updateArithmeticExpression() {
  120. StringBuilder ArithmeticExpression = new StringBuilder();
  121. String operator;
  122. double operand;
  123. for (int i = 0; i < numberList.size(); i++) {
  124. operator = Character.toString(operatorList.get(i));
  125. operand = numberList.get(i);
  126. ArithmeticExpression.append(operator).append(operand);
  127. }
  128. this.arithmeticExpression = ArithmeticExpression.toString();
  129. }
  130. private void roundAllNumbers(int n) {
  131. ArrayList<Double> roundedNumberList = new ArrayList<>();
  132. double number;
  133. for (double numberToRound : numberList) {
  134. number = numberToRound * Math.pow(10, n);
  135. number = Math.round(number);
  136. number = number / Math.pow(10, n);
  137. roundedNumberList.add(number);
  138. }
  139. numberList = roundedNumberList;
  140. }
  141. private void simplifyArithmeticExpression() {
  142. getNumbers();
  143. simplifyAdditionSubtractionOperators();
  144. simplifyMultiplicationDivisionOperators();
  145. getActualNumbers();
  146. operatorList.removeIf(operator -> operator == '-');
  147. updateArithmeticExpression();
  148. roundAllNumbers(5);
  149. }
  150. public double evaluate() throws SyntaxException,MathException {
  151. double result ;
  152. try {
  153. simplifyArithmeticExpression();
  154. evaluateMultiplicationDivision();
  155. evaluateAdditionSubtraction();
  156. result = numberList.get(0);
  157. } catch (IndexOutOfBoundsException e) {
  158. this.arithmeticExpression = "Syntax Error";
  159. throw new SyntaxException();
  160. }
  161. finally {
  162. chackForMathException();
  163. }
  164. return result;
  165. }
  166. public static void main(String[] args) {
  167. String ArithmeticExpression;
  168. double result;
  169. while (true) {
  170. ArithmeticExpression = getArithmeticExpression();
  171. if (ArithmeticExpression.equalsIgnoreCase("EXIT"))
  172. break;
  173. Calculator Calculator = new Calculator(ArithmeticExpression);
  174. try {
  175. try {
  176. result = Calculator.evaluate();
  177. System.out.println(" Answer = " + result);
  178. }catch (MathException e){
  179. System.out.println(e.getMessage());
  180. }
  181. } catch (SyntaxException e) {
  182. System.out.println(e.getMessage());
  183. }
  184. }
  185. }
  186. private void chackForMathException() throws MathException{
  187. double limit = 9.999999999999E12;
  188. for(double devialValue : numberList)
  189. if(!(devialValue<=limit)){
  190. throw new MathException();
  191. }
  192. }
  193. static class MathException extends Throwable{
  194. public MathException(){}
  195. @Override
  196. public String getMessage() {
  197. return "Math Error : Can't perform operation";
  198. }
  199. }
  200. static class SyntaxException extends Throwable {
  201. public SyntaxException() {}
  202. @Override
  203. public String getMessage() {
  204. return "Syntax Error !";
  205. }
  206. }
  207. }

字符串

展开查看全部

相关问题