英文:
Perform arithmetic operations using elements in list
问题
我需要使用列表中的元素执行算术运算。例如,如果我有一个元素列表[25,+,5,-,8,/,4],我如何将其转换为形式为25+5-(8/4)的算术运算,并打印其结果(在这个示例中为28)?我使用的列表类型为String。请任何人帮助我解决这个问题。我对ArrayList和其他内容都很陌生。
英文:
I need to perform arithmetic operations using the elements in a list. For example, if I have a list of elements [25, +, 5, -, 8, /, 4] how can I convert this as an arithmetic operation in the form 25+5-(8/4) and print its result (28 in this example)? The list I used is of type String. Anyone, please help me to solve this problem. I am new to Arraylist and all.
答案1
得分: 0
以下是翻译好的内容:
一个表达式作为列表:
List<String> expression = new ArrayList();
Collections.addAll(expression, "25", "+", "5", "-", "8", "/", "4");
现在你需要执行操作,直到只剩下一个项。
你可以像人一样进行评估:首先处理 * 和 /,然后处理 + 和 -。
有很多种方式来编写这个过程。
while (expression.size() > 1) {
int terms = expression.size();
// ... 简化表达式:
// 1. * 和 /:
...
if (expression.size() < terms) {
continue;
}
// 2. + 和 -:
for (int i = 1; i + 1 < expression.size(); i += 2) {
String operator = expression.get(i);
switch (operator) {
case "+":
int lhs = Integer.parseInt(expression.get(i - 1));
int rhs = Integer.parseInt(expression.get(i + 1));
int n = lhs + rhs;
expression.remove(i);
expression.remove(i + 1);
expression.set(i - 1, String.valueOf(n));
i -= 2; // 保持在当前操作符位置。
break;
...
}
}
if (expression.size() == terms) {
System.out.println("无法简化表达式:" + expression);
break;
}
}
String result = expression.get(0);
System.out.println(result);
编写你自己的循环。上面的代码不一定非常逻辑清晰。
英文:
An expression as List:
List<String> expression = new ArrayList();
Collections.addAll(expression, "25", "+", "5", "-", "8", "/", "4");
Now you have to do operations till there is just one term.
You can do the evaluation as a human: first look at * and /, then at + and -.
There are really many variants to write this.
while (expression.size() > 1) {
int terms = expression.size();
// ... reduce expression:
// 1. * and /:
...
if (expression.size() < terms) {
continue;
}
// 2. + and -:
for (int i = 1; i + 1 < experesssion.size(); i += 2) {
String operator = experesssion.get(i);
switch (operator) {
case "+":
int lhs = Integer.parseInt(expression.get(i - 1));
int rhs = Integer.parseInt(expression.get(i + 1));
int n = lhs + rhs;
expression.remove(i);
expression.remove(i +1);
expression.set(i - 1, String.valueOf(n));
i -= 2; // Keep at this operator position.
break;
...
}
}
if (expression.size() == terms) {
System.out.println("Could not reduce expression: " + expression);
break;
}
}
String result = expression.get(0);
System.out.println(result);
Write your own loop(s). The code aboveis not necessarily very logical.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论