題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。
程序分析:我們想辦法把最小的數放到x上,先將x與y進行比較,如果x> y則將x與y的值進行交換,然后再用x與z進行比較,如果x> z則將x與z的值進行交換,這樣能使x最小。
1 package com.li.FiftyAlgorthm; 2 3 import java.util.Scanner; 4 5 /** 6 * 題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。 程序分析:我們想辦法把最小的數放到x上,先將x與y進行比較,如果x>y 7 * 則將x與y的值進行交換,然后再用x與z進行比較,如果x> z則將x與z的值進行交換,這樣能使x最小。 8 * @author yejin 9 */ 10 public class NumberCompare { 11 public static void main(String[] args) { 12 NumberCompare nc = new NumberCompare(); 13 int a, b, c; 14 15 System.out.println("Input 3 numbers:"); 16 a = nc.input(); 17 b = nc.input(); 18 c = nc.input(); 19 // 20 // fnc.compare(a, b);//方法調用不能通過改變形參的值來改變實參的值 21 // fnc.compare(b, c);// 這種做法是錯的 22 // fnc.compare(a, c); 23 // System.out.println("result:" + a +" " + b + " " + c);// 沒有改變 24 25 if (a > b) { 26 int t = a; 27 a = b; 28 b = t; 29 } 30 31 if (a > c) { 32 int t = a; 33 a = c; 34 c = t; 35 } 36 37 if (b > c) { 38 int t = b; 39 b = c; 40 c = t; 41 } 42 System.out.println(a + " " + b + " " + c); 43 } 44 45 public int input() { 46 int value = 0; 47 Scanner s = new Scanner(System.in); 48 value = s.nextInt(); 49 return value; 50 } 51 52 public void compare(int x, int y) {// 此方法沒用 53 if (x > y) { 54 int t = x; 55 x = y; 56 y = t; 57 } 58 } 59 }