其他分享
首页 > 其他分享> > if例题2

if例题2

作者:互联网

以下内容为本人在b站尚硅谷java学习课的学习笔记,给以后的自己当个小丑,也可以和各位分享分享!!!

遇事不决三步走~~~

①:数据输入

import java.util.Scanner;
class Text2 {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入要排序的三个整数:");
		int num1 = scan.nextInt();
		int num2 = scan.nextInt();
		int num3 = scan.nextInt();

②:排序(以下是我根据例题自己的思路,底下有尚硅谷课程老师的思路)

        类似与冒泡法,先将num1与num2比较;如果num1 > num2 ,运用中间变量temp,交换num1与num2的数值;然后,再由num2与num3比较,如果num2 > num3,运用中间变量temp,交换num2与num3的数值;最后,不要忘记!!! 还要再比较一次num1与num2;结果按顺序输出num1, num2, num3;

int temp;
		if(num1 > num2){
			temp = num1;
			num1 = num2;
			num2 = temp;
		} 
		if(num2 > num3){
			temp = num2;
			num2 = num3;
			num3 = temp;
		}
		if(num1 > num2){
			temp = num1;
			num1 = num2;
			num2 = temp;
		}
		System.out.println("这三个数从小到大依次为:" + num1 + "," + num2 + "," + num3);

③:编译运行

方法二 :尚硅谷老师的判断思路,非常妙!!!

 运用了if语句的嵌套,如果num1 > num2,排序结果就是:( )num2 ( ) num1 ( ) ;注:括号内的为num3,紧接着嵌套if

如果num3 >= num1; 输出结果:num2 < num1 < num3;

如果num3 <= num2;输出结果:num3 < num2 < num1;

否则:输出结果:num2 < num3 < num1; (此时内部的if执行完毕)

否则(num1 < num2):排序结果就是:( )num1 ( ) num2 ( )以下if嵌套思路与上面一致;

//方法二:
		if(num2 >= num1){		//__num1__num2__
			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);
			}
		}else{		//__num2__num1__
			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);
			}
		}

说明:

        ①if语句是可以嵌套的;

        ②如果if-else下面的语句只有一句 花括号可以省略,但不建议!

标签:num1,temp,num3,System,println,例题,num2
来源: https://blog.csdn.net/weixin_47877038/article/details/122491659