问题描述
编写一个程序,输入两个整数,分别存放在变量x和y当中,然后使用自己定义的函数swap来交换这两个变量的值。
输入格式:输入只有一行,包括两个整数。
输出格式:输出只有一行,也是两个整数,即交换以后的结果。
要求
主函数负责数据的输入与输出,但不能直接交换这两个变量的值,必须通过调用单独定义的函数swap来完成,而swap函数只负责交换变量的值,不能输出交换后的结果。
输入输出样例
样例输入
4 7
样例输出
7 4
思路
在c中,可以直接向函数中传参数的地址
在Java中,没有指针的概念,但是可以引用对象
将两个数作为一个对象的属性值,可以做到交换
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m = input.nextInt();
int n = input.nextInt();
Swap sp = new Swap(m, n);
sp.swap();
System.out.println(sp.m + " " + sp.n);
}
private static class Swap {
int m;
int n;
public Swap(int m, int n) {
this.m = m;
this.n = n;
}
public void swap() {
int temp = this.m;
this.m = this.n;
this.n = temp;
}
}
}