[英]A calculator with no if's
所以我想问一下是否可以制作一个计算器,但没有像往常一样的 if 语句,我这样做:
Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
if(operator.equals(+))
{
double result = number1 + number2;
System.out.println("The result is " + result);
}
我需要做一个 if 语句并“询问”运算符是否等于加号。 是否有可能使您不需要使用 if 语句并这样做:
Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
System.out.println("The result is " number1 + operator + number2);
现在它只是作为例子说:结果是 15+17,我想问一下是否有可能使它在没有 if 语句的情况下给我结果。 谢谢
可以使用 no if
、 no switch
和其他分支语言结构来做到这一点*。 基本思想是使用一个函数映射来进行操作,然后使用运算符(作为字符串)在映射中查找函数。
import java.util.Map;
import java.util.HashMap;
import java.util.function.BinaryOperator;
public class Calculator {
private static final Map<String, BinaryOperator<Integer>> operators;
static {
operators = new HashMap<>();
operators.put("+", (a, b) -> a + b);
operators.put("-", (a, b) -> a - b);
operators.put("*", (a, b) -> a * b);
operators.put("/", (a, b) -> a / b);
}
public static int doOperation(int a, int b, String op) {
return operators.get(op).apply(a, b);
}
}
这只是为了演示这个概念,所以我没有做任何控制台输入/输出或解析,也没有错误处理。 如果字符串op
不在地图中,它将抛出NullPointerException
; 如果您愿意,可以使用getOrDefault
来处理这种情况。
*是的,当然有分支,以使引擎盖下要去get
和getByDefault
工作。 我的意思是,这段代码本身不使用任何编译为条件跳转的语言结构。
这是一个部分模型。 它没有对无效输入进行所有必要的错误控制,并且只支持一个操作符。 但这是一个开始。
Scanner input = new Scanner(System.in);
boolean more = true;
while (more) {
int result = 0;
System.out.print(
"Enter two ints separated by spaces");
int a = input.nextInt();
int b = input.nextInt();
System.out.println("Enter the operator");
String c = input.next();
switch (c) {
case "+":
System.out.println(a + b);
break;
default:
System.out.println("Unknown operator");
}
System.out.print("Another? ");
String answer = input.next();
switch (answer.charAt(0)) {
case 'n':
case 'N':
more = false;
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.