java三目運算子、分支、陣列方法,解決整數比較大小問題
阿新 • • 發佈:2018-12-09
程式碼塊
程式碼如下,例如:
//class前,匯入的java包
import java.util.Scanner;
//我只把主方法列出來了
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 接收使用者輸入
System.out.println("清輸入第1個數:");
int a = scanner.nextInt();
System.out.println("清輸入第2個數:");
int b = scanner.nextInt();
System.out.println("清輸入第3個數:");
int c = scanner.nextInt();
System.out.println("清輸入第4個數:");
int d = scanner.nextInt();
// 三目運算解決
int m = a > b ? a : b;
int n = c > d ? c : d;
int x = m > n ? m : n;
System.out.println("max=" + x);
// 分支方法解決
int t;
if (a > b) { t = a; a = b; b = t; }
if (a > c) { t = a; a = c; c = t; }
if (a > d) { t = a; a = d; d = t; }
if (b > c) { t = b; b = c; c = t; }
if (b > d) { t = b; b = d; d = t; }
if (c > d) { t = c; c = d; d = t; }
System.out.println("max=" + d);
// 陣列方法解決
int p[] = new int[4];
for (int i = 0; i < 4; i++) {
System.out.println("請輸入第" + (i + 1) + "個數字:");
p[i] = scanner.nextInt();
}
for (int i = 0; i < 3; i++) {
if (p[i] > p[i + 1]) {
// 這裡也可以設定一箇中間變數t來進行交換
p[i] = p[i] + p[i + 1];
p[i + 1] = p[i] - p[i + 1];
p[i] = p[i] - p[i - 1];
}
}
System.out.println("max=" + p[3]);// 最大的就放在陣列最後了
}
說明
- 目前,本人只是個小白,所以高手誤噴,謝謝合作。
- 以上是本人整理總結的幾種方法,嘿嘿。
- 目的只是為了大家共同交流學習,有不足之處,還請指出。