从键盘输⼊三个数,按从⼤到⼩进⾏输出的⼏种⽅法1. 第⼀种使⽤if语句来完成这个功能
1public static void main(String[] args) {
2 Scanner in = new Scanner(System.in);
3 System.out.println("请输⼊第⼀个数:");
4int num1 = in.nextInt();
nextint()方法5 System.out.println("请输⼊第⼆个数:");
6int num2 = in.nextInt();
7 System.out.println("请输⼊第三个数:");
8int num3 = in.nextInt();
9//定义临时变量转换为num1>num2>num3
10int temp = 0;
11if (num1 < num2)
12 {
13 temp = num1;
14 num1 = num2;
15 num2 = temp;
16 }
17if (num1 < num3)
18 {
19 temp = num1;
20 num1 = num3;
21 num3 = num1;
22 }
23if (num2 < num3)
24 {
25 temp = num2;
26 num2 = num3;
27 num3 = temp;
28 }
29 System.out.println("三个数从⼤到⼩的数字是:"+num1+"\t"+num2+"\t"+num3);
30 }
2. 使⽤三⽬运算符来完成这个功能
1public static void main(String[] args) {
2 Scanner in = new Scanner(System.in);
3 System.out.println("请输⼊第⼀个数:");
4int num1 = in.nextInt();
5 System.out.println("请输⼊第⼆个数:");
6int num2 = in.nextInt();
7 System.out.println("请输⼊第三个数:");
8int num3 = in.nextInt();
9int max = (num1>num2)?num1:num2;
10//得到的最⼤值再与剩下的数⽐较
11 max = (max>num3)?max:num3;
12int min = (num1<num2)?num1:num2;
13 min = (min<num3)?min:num3;
14//三个数相加减去最⼤值和最⼩值,就是中间值
15int mid = num1 + num2 + num3 - min -max;
16 System.out.println("三个数从⼤到⼩的数字是:"+max+"\t"+mid+"\t"+min);
17
18 }
3. 使⽤数组的⽅式,进⾏冒泡排序来完成这个功能、
1public static void main(String[] args) {
2 Scanner in = new Scanner(System.in);
3 System.out.println("请输⼊第⼀个数:");
4int num1 = in.nextInt();
5 System.out.println("请输⼊第⼆个数:");
6int num2 = in.nextInt();
7 System.out.println("请输⼊第三个数:");
8int num3 = in.nextInt();
9//使⽤数组接收三个得到的三个数
10int arr[] = {num1,num2,num3};
11for (int i = 0;i<arr.length - 1 ;i++ )
12 {
13for (int j = 0;j<arr.length-1-i ;j++ )
14 {
15if (arr[j] < arr[j+1])
16 {
17int temp = arr[j+1];
18 arr[j+1] = arr[j];
19 arr[j] = temp;
20 }
21 }
22 }
23 System.out.println("三个数从⼤到⼩的数字是:"+ String(arr));
24 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论