如果任一值範圍內,您的代碼返回較大值。
鑑於這些問題的性質,您應該嘗試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