Java崩溃了

时间:2015-10-26 21:23:47

标签: java

我想确切知道这些if语句是如何切换数字的。我之前从未被要求做过非降序排序,因此我从互联网上抓了一小段。

import java.util.Scanner;

/**
 * Created by Nicholas on 10/26/2015.
 */
public class Main {

    final static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {

        System.out.println("Please enter three numbers.");
        System.out.println();

        System.out.print("Number 1: ");
        int num1 = userInput.nextInt();
        System.out.println();

        System.out.print("Number 2: ");
        int num2 = userInput.nextInt();
        System.out.println();

        System.out.print("Number 3: ");
        int num3 = userInput.nextInt();
        System.out.println();

        if (num1 > num2) {
            int temp = num1;
            num1 = num2;
            num2 = temp;
        }

        if (num2 > num3) {
            int temp = num2;
            num2 = num3;
            num3 = temp;
        }

        if (num1 > num2) {
            int temp = num1;
            num1 = num2;
            num2 = temp;
        }

        System.out.print("The numbers in non-descending order are, " + num1 + " " + num2 + " " + num3);
    }
}

1 个答案:

答案 0 :(得分:0)

if语句通过创建临时值来存储旧号码,然后将其设置为新号码,然后将另一个号码设置为旧的已保存号码

更有趣的切换数字的方法是使用按位运算符

num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;

这可以通过将这些位合并在一起,并且因为xor在赋予相同值时会反转((A xor B) xor B) == A