题目:输入三个整数x,y,z,请把这三个数从小到大输出。
分析:x与y进行比较,小的变为x,大的变为y;再让y与z进行比较,小的变为y,大的变为z;最后让x与y进行比较,因为y可能已经变为了新的值,需要再与x比较一下,把小的变为x,大的变为y。
代码:
import java.util.*;
public class Practice15 {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("请输入整数x,y,z:"); //输入x,y,z
int x = s.nextInt();
int y = s.nextInt();
int z = s.nextInt(); //键盘输入x,y,z
sort(x,y,z); //调用sort()方法输出排序后的结果
s.close();
}
public static void sort(int x,int y, int z){
int t; //定义中间变量
if(x > y){ //如果x>y,将x和y交换
t = x;
x = y;
y = t;
}
if(y > z){ //如果y>z,将y和z交换
t = y;
y = z;
z = t;
}
if(x > y){ //如果x>y,将x和y交换
t = x;
x = y;
y = t;
}
System.out.println("从小到大排序后的结果是:" + x + "," + y + "," + z); //输出排序后的结果
}
}
结果: