1 回答
TA贡献1785条经验 获得超8个赞
假设BEAKandCLAW是整数并且COLOR是 a String,那么表格可以更像:
// must be grey
if ("Grey".equals(COLOR)) {
if ((BEAK_MM == 1 && CLAW_MM == 0)
|| (BEAK_MM == 2 && CLAW_MM == 1)
|| (BEAK_MM == 3 && CLAW_MM AW == 2)
|| (BEAK_MM == 4 && CLAW_MM == 3)
|| ( (BEAK_MM == 4 || BEAK_MM == 5) && CLAW_MM == 4))) {
System.out.println("The bird is the word");
}
}
这里的逻辑是,根据表格,鸟A型一定是灰色的。然后有一些关于喙和爪类型的特定检查,但如果它不是灰色,则它不是 A 型鸟。也不需要所有 OP 堆叠的“else if”语句。
有许多其他方法可以解决问题空间,但我没有数组的限制,因此大概没有其他有用的数据结构,例如Listor Set。
正如@Nicholas K 所指出的,String对象必须与.equals().
我也会把这些东西移到一个方法上 isBirdTypeA(int beak, int claw, String color) { ... }
@Test
public void testBirds()
{
final String G = "Grey";
final String P = "Pink";
assertTrue(isBirdTypeA(1, 0, G));
assertFalse(isBirdTypeA(1, 0, P));
assertTrue(isBirdTypeA(2, 1, G));
assertTrue(isBirdTypeA(3, 2, G));
assertTrue(isBirdTypeA(4, 3, G));
assertTrue(isBirdTypeA(4, 4, G));
assertTrue(isBirdTypeA(5, 4, G));
assertFalse(isBirdTypeA(4, 5, G));
assertFalse(isBirdTypeA(4, 0, G));
assertFalse(isBirdTypeA(1, 1, G));
}
private static boolean isBirdTypeA(int beak, int claw, String color)
{
if ("Grey".equals(color)) {
if ((beak == 1 && claw == 0)
|| (beak == 2 && claw == 1)
|| (beak == 3 && claw == 2)
|| (beak == 4 && claw == 3)
|| ( (beak == 4 || beak == 5) && claw == 4)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int BEAK_MM = Integer.parseInt(args[0]);
int CLAW_MM = Integer.parseInt(args[1]);
String COLOR = args[2];
if (isBirdTypeA(BEAK_MM, CLAW_MM, COLOR)) {
System.out.println("The type of bird is A");
}
}
$ java BirdBeak 1 0 Gray
鸟的类型是 A
添加回答
举报