【程序15】
题目:输入三个整数x,y,z,请把这三个数由小到大输出。
1.程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
- import java.util.*;
- public class Test015
- {
- public static void main(String[] args)
- {
- int x,y,z;
- Scanner in = new Scanner(System.in);
- System.out.print("请输入第一个数:");
- x = in.nextInt();
- System.out.print("请输入第二个数:");
- y = in.nextInt();
- System.out.print("请输入第三个数:");
- z = in.nextInt();
- ThreeNumberSort tns = new ThreeNumberSort(x,y,z);
- tns.NumberSorting();
- tns.ShowSortResult();
- }
- }
- class ThreeNumberSort
- {
- private int a,b,c;
- private int temp = 0;
- public ThreeNumberSort(int a,int b, int c)
- {
- this.a = a;
- this.b = b;
- this.c = c;
- }
- public void NumberSorting()
- {
- while(true)
- {
- if(a>b)
- {
- temp = a;
- a = b;
- b = temp;
- }
- if(b>c)
- {
- temp = b;
- b = c;
- c=temp;
- }
- if(a<b && b<c)
- {
- break;
- }
- }
- }
- public void ShowSortResult()
- {
- System.out.println("排序后的顺序为:" + a + ", " +b+", "+ c );
- }
- }
转载于:https://blog.51cto.com/shylx123/555141