问题描述
大家好,
我这里有这个简单的计算器。目前,它只接受两个整数和一个运算符。我想接受两个以上的整数(无限)。请记住,我不是在寻找操作顺序,只是从左到右。我考虑过递归,但不知道如何去做。
Hi everyone,
I have this simple calculator here. At the moment, it only accepts two integers and an operator. I want to accept more than two integers (infinite). Keep in mind I am not looking for order of operations, just left to right. I thought about recursion, but not sure how to go about it.
import java.util.Scanner;
public class Calc24 {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter an expression of the form 3 m 5");
int n1 = scanner.nextInt();
String operation = scanner.next();
int n2 = scanner.nextInt();
switch (operation) {
case "a":
System.out.println("Your answer is " + (n1 + n2));
break;
case "s":
System.out.println("Your answer is " + (n1 - n2));
break;
case "d":
System.out.println("Your answer is " + (n1 / n2));
break;
case "m":
System.out.println("Your asnwer is " + (n1 * n2));
break;
default:
System.out.println("Je ne sais pas");
}
}
}
}
推荐答案
17 + 3 - 11 * 44 / 6
阅读前三项( operand1
操作
operand2
)
进行计算并将答案保存为新的 operand1
。
获取接下来的两项(操作
operand2
)
进行计算并将答案保存为新 operand1
。
重复直到没有更多项目。
一旦实施并了解到那时你可以考虑使用运算符优先级,括号等。
Read first three items (operand1
operation
operand2
)
Do the calculation and save the answer as the new operand1
.
Get the next two items (operation
operand2
)
Do that calculation and save the answer as the new operand1
.
Repeat until no more items.
Once you have implemented and understood that then you can think about using operator precedence, parentheses etc.
这篇关于简单(从左到右)计算器Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!