這個問題似乎是一個思維練習所以考慮這個答案替代其他正確答案供您考慮。這裏是我的企業解決方案。
步驟0,重構代碼,使其可測試和存根出來,會做實際的工作方法:
import static java.lang.System.in;
import static java.lang.System.out;
import java.util.Scanner;
public class DescendingOrder {
public static final void main(final String... args) { // unavoidable use of an array, please don't dock points
try (final Scanner kbd = new Scanner(in)) { // always close your Closeables
final int a = kbd.nextInt();
final int b = kbd.nextInt();
final int c = kbd.nextInt();
final DescendingOrder calculator = new DescendingOrder();
out.println(calculator.order(a, b, c));
}
}
public String order(final int a, final int b, final int c) {
return null;
}
}
步驟1,編寫單元測試:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DescendingOrderTest {
private DescendingOrder orderer;
@Before
public void setUp() throws Exception {
orderer = new DescendingOrder();
}
@Test
public final void testOrderABC() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE); // don't forget the edge cases
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
@Test
public final void testOrderACB() {
final String result = orderer.order(13, 5, 8);
assertEquals("13 8 5", result);
}
@Test
public final void testOrderBAC() {
final String result = orderer.order(4, 8, 2);
assertEquals("8 4 2", result);
}
@Test
public final void testOrderBCA() {
final String result = orderer.order(-8, -2, -4); // don't forget negative numbers
assertEquals("-2 -4 -8", result);
}
@Test
public final void testOrderCAB() {
final String result = orderer.order(1, -5, 5);
assertEquals("5 1 -5", result);
}
@Test
public final void testOrderCBA() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE);
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
@Test
public final void testAllSame() {
final String result = orderer.order(53, 53, 53);
assertEquals("53 53 53", result);
}
}
第2步,反覆地執行命令,直到你的測試都通過了:
public String order(final int a, final int b, final int c) {
if (a > b && a > c) {
return a + " " + order(b, c);
} else if (b > a && b > c) {
return b + " " + order(a, c);
}
return c + " " + order(a, b);
}
protected String order(final int x, final int y) {
if (x > y) {
return x + " " + y;
}
return y + " " + x;
}
它可能不是最計算effici ent,但我保持方法的大小很小,所以很清楚代碼是要完成的。我也不需要瀏覽六個場景,看看它是否正確。如果我假設order(int, int)
是正確的,那麼我只需要通過三種方案來查看order(int, int, int)
是否正確。
很顯然,這是矯枉過正。但是這些限制永遠不會存在。
這是5還是3?你的文字說一件事,你的代碼說另一件事。 –
此外,如果您嘗試以降序輸出數字,則上述代碼不起作用。你打印的是所有三個整數的總和,不管它們是什麼會相同(加法順序不影響輸出) – Gacci
@Gacci如何讓系統輸出打印行以降序顯示數字。和它的3個數字對此表示歉意 –