例题课本例题3-1转换==整数从大到小排序
2023-09-27 14:27:29 时间
问题:
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);
}
}
}
运行结果:
总结:
输入的三个数可以用回车表示一个数的输入,也可以用空格表示一个数的输入。