题目
您的任务是创建一个执行四个基本数学运算的函数。
该函数应该有三个参数 - operation(string / char),value1(number),value2(number)。
应用所选操作后,该函数应返回数字的结果。
例子:
basicOp('+', 4, 7) // Output: 11
basicOp('-', 15, 18) // Output: -3
basicOp('*', 5, 5) // Output: 25
basicOp('/', 49, 7) // Output: 7
测试用例:
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.runners.JUnit4;
public class SolutionTest
{
BasicOperations basicOps = new BasicOperations();
@Test
public void testBasics()
{
System.out.println("Basic Tests");
assertThat(basicOps.basicMath("+", 4, 7), is(11));
assertThat(basicOps.basicMath("-", 15, 18), is(-3));
assertThat(basicOps.basicMath("*", 5, 5), is(25));
assertThat(basicOps.basicMath("/", 49, 7), is(7));
}
}
解题
My
public class BasicOperations
{
public static Integer basicMath(String op, int v1, int v2)
{
int v3 = 0;
if ("+".equals(op)) {
v3 = v1 + v2;
} else if ("-".equals(op)) {
v3 = v1 - v2;
} else if ("*".equals(op)) {
v3 = v1 * v2;
} else if ("/".equals(op)) {
v3 = v1 / v2;
}
return v3;
}
}
Other
public class BasicOperations
{
public static Integer basicMath(String op, int v1, int v2)
{
switch (op) {
case "-":
return v1 - v2;
case "+":
return v1 + v2;
case "*":
return v1 * v2;
case "/": {
if (v2 == 0)
throw new IllegalArgumentException("Division by zero");
return v1 / v2;
}
default:
throw new IllegalArgumentException("Unknown operation: " + op);
}
}
}
后记
身为测试,自叹不如,看看别人的代码考虑多周全呀。
网友评论