例题课本例题3-1转换==整数从大到小排序

来源:互联网 发布:java 自定义函数 编辑:程序博客网 时间:2024/05/16 17:35

问题:

Number类创建的对象可以将三个整数从小到大排序,主类负责让用户从键盘输入三个数,然后调用Number类创建的对象对用户输入的整数进行排序。


代码:

Test.java

import java.util.Scanner;public class Test {    public static void main(String[]args){        System.out.println("please enter three numbers:");        Scanner reader=new Scanner(System.in);        int x=reader.nextInt();        int y=reader.nextInt();        int z=reader.nextInt();        Number order=new Number();        order.sort(x,y,z);        }}

Number.java

public class Number {    public void sort(int a,int b,int c){        int count=0;        int temp=0;        if(a>b){//判断了第一个和第二个的大小,保证第一个小于第二个        temp=a;        a=b;        b=temp;        count+=1;        System.out.println("The oder of the  "+count+"  time is :"+a+"  "+b+"  "+c);        }        if(a>c){//判断了第一个和第三个的大小,这样可以保证调出来第一个是最小的            temp=a;            a=c;            c=temp;            count+=1;            System.out.println("The oder of the  "+count+"  time is :"+a+"  "+b+"  "+c);        }                if(b>c){            temp=b;            b=c;            c=temp;            count+=1;            System.out.println("The oder of the  "+count+"  time is :"+a+"  "+b+"  "+c);        }    }}


运行结果:







总结:

输入的三个数可以用回车表示一个数的输入,也可以用空格表示一个数的输入。

0 0
原创粉丝点击