如果任一值范围内,您的代码返回较大值。
鉴于这些问题的性质,您应该尝试test driven approach来开发您的方法,这也可以确保您的代码按照您的预期行事。类似于以下内容的测试可能是您在CodingBat上提交时测试您的代码的测试。
public class SandBox {
public int max1020(int a, int b) {
if (10 <= a && a <= 20) { // if a is in range
if (a >= b || b > 20) { // if a is greater than B or B is out of range
return a;
}
}
//
if (10 <= b && b <= 20) { // if b is in range
return b;
}
return 0;
}
}
测试
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SandBoxTest {
SandBox sand;
@Before
public void given(){
sand = new SandBox();
}
@Test
public void testOne(){
int i = sand.max1020(1, 2);
assertThat(i, is(0));
}
@Test
public void testTwo(){
int i = sand.max1020(2, 1);
assertThat(i, is(0));
}
@Test
public void testThree(){
int i = sand.max1020(5, 10);
assertThat(i, is(10));
}
@Test
public void testFour(){
int i = sand.max1020(10, 5);
assertThat(i, is(10));
}
@Test
public void testFive(){
int i = sand.max1020(11, 15);
assertThat(i, is(15));
}
@Test
public void testSix(){
int i = sand.max1020(15, 11);
assertThat(i, is(15));
}
@Test
public void testSeven(){
int i = sand.max1020(20, 23);
assertThat(i, is(20));
}
@Test
public void testEight(){
int i = sand.max1020(23, 20);
assertThat(i, is(20));
}
@Test
public void testNine(){
int i = sand.max1020(33, 25);
assertThat(i, is(0));
}
@Test
public void testTen(){
int i = sand.max1020(25, 33);
assertThat(i, is(0));
}
}
尝试写你的比较作为'(10 = 2013-05-03 21:19:36
检查范围后,您查找两个数字的最大值 示例21,19 19在范围内,但21不是,如果条件通过,但您返回的最大值是21,请注意21不在范围内。 – user2281527 2013-05-03 21:22:28
我不知道在写这里的时候是否错过了它,但是在第二个if之前应该有'else'。还有其他问题,但你应该先解决这个问题。 – SOfanatic 2013-05-03 21:22:39