给定两个整形变量的值,将两个值的内容进行交换。
一、代码
1.设置临时变量temp
import java.util.Scanner;
public class ExchangeNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please input the first number:");
int n1 = input.nextInt();
System.out.print("Please input the second number:");
int n2 = input.nextInt();
int temp = 0;
if(n1==n2)
System.out.print(n1+" "+n2);
if(n1!=n2) {
temp = n1;
n1 = n2;
n2 = temp;
System.out.print(n1+" "+n2);
}
}
}
2.无临时变量
import java.util.Scanner;
public class ExchangeNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please input the first number:");
int n1 = input.nextInt();
System.out.print("Please input the second number:");
int n2 = input.nextInt();
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
System.out.print(n1+" "+n2);
}
}
二、结果