题目
Jenny编写了一个为用户返回问候语的函数。然而,她爱上了约翰尼,并希望与他略微不同。她在她的功能中添加了一个特例,但她犯了一个错误。
你能救她吗?
这题目真感性!
public class Greeter {
public static String greet(String name) {
return String.format("Hello, %s!", name);
if(name.equals("Johnny")){
return "Hello, my love!";
}
}
}
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
@Test
public void Test() {
assertEquals("should greet some people normally", "Hello, Jim!", Greeter.greet("Jim"));
assertEquals("should greet some people normally", "Hello, Jane!", Greeter.greet("Jane"));
assertEquals("should greet some people normally", "Hello, Simon!", Greeter.greet("Simon"));
assertEquals("should greet Johnny a little bit more special", "Hello, my love!", Greeter.greet("Johnny"));
}
}
解题
My
public class Greeter {
public static String greet(String name) {
if(name.equals("Johnny")){
return "Hello, my love!";
}
return String.format("Hello, %s!", name);
}
}
Other
public class Greeter {
public static String greet(String name) {
if (!name.isEmpty()) {
if (name.equals("Johnny"))
return "Hello, my love!";
else
return String.format("Hello, %s!", name);
}
return "name is null";
}
}
public class Greeter {
public static String greet(String name) {
return "Hello, " + (name == "Johnny" ? "my love" : name) + "!";
}
}
后记
这题的测试用例确实没有考虑为null的情况。
网友评论