如何重新创建下表?

时间:2018-10-11 16:38:20

标签: java arrays if-statement

enter image description here

大家好,我正在尝试重新创建分配表,由于与&&函数有关的错误,我被卡住了。请注意,我们不允许使用数组,并且仅限于“ switch”和“ If”

这是到目前为止我得到的:

if ((BEAK_MM == 1) && (CLAW_MM == 0) && (COLOR = "Grey")) {
   System.out.println ("The type of bird is A.");}
else if ((BEAK_MM == 2) && (CLAW_MM == 1) && (COLOR = "Grey")) 
   System.out.println ("The type of bird is A.");}
else if ((BEAK_MM == 3) && (CLAW_MM == 2) && (COLOR = "Grey")) 
   System.out.println ("The type of bird is A.");}
else if ((BEAK_MM == 4) && (CLAW_MM == 3) && (COLOR = "Grey")) 
   System.out.println ("The type of bird is A.");}
else if ((BEAK_MM <= 4.5) && (CLAW_MM == 4) && (COLOR = "Grey")) 
   System.out.println ("The type of bird is A.");}

1 个答案:

答案 0 :(得分:0)

假设BEAKCLAW是整数,而COLORString,则该表的排列方式应类似于:

// 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”语句。

还有许多其他方法可以解决问题空间,但是我在没有数组的情况下进行限制,因此大概没有其他有用的数据结构,例如ListSet

如@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灰色
  鸟的类型是A