Java基本语法-if-else的例题 对三个数进行从小到大排序方法

编写程序:由键盘输入三个整数分别存入变量num1、num2、num3,
对它们进行排序(使用 if-else if-else),并且从小到大输出。

方法一

import java.util.Scanner;

class IfTest3{
	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);

		System.out.println("请输入第一个整数:");
		int num1 = scan.nextInt();
		System.out.println("请输入第二个整数:");
		int num2 = scan.nextInt();
		System.out.println("请输入第三个整数:");
		int num3 = scan.nextInt();
		if(num1 < num2 && num1 < num3){
			if(num2 < num3){
				System.out.println("排序后的数为:" + num1 + " " + num2 + " " + num3);
			}else{
				System.out.println("排序后的数为:" + num1 + " " + num3 + " " + num2);
			}
		}else if(num2 < num1 && num2 < num3){
			if(num1 < num3){
				System.out.println("排序后的数为:" + num2 + " " + num1 + " " + num3);
			}else{
				System.out.println("排序后的数为:" + num2 + " " + num3 + " " + num1);
			}
		}else if(num3 < num1 && num3 < num2){
			if(num1 < num2){
				System.out.println("排序后的数为:" + num3 + " " + num1 + " " + num2);
			}else{
				System.out.println("排序后的数为:" + num3 + " " + num2 + " " + num1);
			}
		}
	}
}

方法二

import java.util.Scanner;

class IfTest2{
	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);

		System.out.println("请输入第一个整数:");
		int num1 = scan.nextInt();
		System.out.println("请输入第二个整数:");
		int num2 = scan.nextInt();
		System.out.println("请输入第三个整数:");
		int num3 = scan.nextInt();

		if(num1 >= num2){
			if(num3 >= num1){
				System.out.println(num2 + "," + num1 + "," + num3);
			}else if(num3 <= num2){
				System.out.println(num3 + "," + num2 + "," + num1);
			}else{
				System.out.println(num2 + "," + num3 + "," + num1);
			}
		}else{
			if(num3 >= num2){
				System.out.println(num1 + "," + num2 + "," + num3);
			}else if(num3 <= num1){
				System.out.println(num3 + "," + num1 + "," + num2);
			}else{
				System.out.println(num1 + "," + num3 + "," + num2);
			}
		}
	}
}

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇