java交换两个数据

一、问题描述

编写一个程序,输入两个整数,分别存放在变量x和y当中,然后使用自己定义的函数swap来交换这两个变量的值。
  输入格式:输入只有一行,包括两个整数。
  输出格式:输出只有一行,也是两个整数,即交换以后的结果。
  要求:主函数负责数据的输入与输出,但不能直接交换这两个变量的值,必须通过调用单独定义的函数swap来完成,而swap函数只负责交换变量的值,不能输出交换后的结果。
输入输出样例
样例输入
4 7
样例输出
7 4

二、 代码实现

经典错误:

import java.util.Scanner;
public class swap{
	public static void main(String[] args){
		int x = 0, y = 0;
		Scanner input = new Scanner(System.in);
		x = input.nextInt();
		y = input.nextInt();
		swap();
		System.out.println(x + " "+ y);
		input.close();
	}
	private static void swap(){
		int temp = x;
		x = y;
		y = temp;
	}
}

看上去似乎没有错,但运行的时候不能实现交换,怎么回事呢?
对于swap()方法,若不采用任何操作的话,在实参传给形参,交换两数数值后,会直接释放,交换后的值带不回去。如何解决呢?

方法一:关键是定义static int x,y; 这两个就是全局变量了,对x,y进行任何操作都可直接更改。

import java.util.Scanner;
public class swap{
	static int x,y;
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		x = input.nextInt();
		y = input.nextInt();
		swap();
		System.out.println(x + " "+ y);
		input.close();
	}
	private static void swap(){
		int temp = x;
		x = y;
		y = temp;
	}
}

方法二:swap()方法利用数组带回到主函数

import java.util.Scanner;
/**
 * 交换两个数据
 * 
 * @author Administrator
 *
 */
public class Swap {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int a  = input.nextInt();
		int b = input.nextInt();
		int []arr = new int[2];
		int []crr = new int[2];
		arr[0] = a;
		arr[1] = b;
		crr = swap(arr[0], arr[1]);
		for(int i = 0; i<crr.length; i++){
			System.out.println(crr[i]);
		}
	}
	
	public static int[] swap(int x, int y){
		int brr[] = new int[2];
		brr[0] = x;
		brr[1] = y;
		int temp = 0;
		temp = brr[0];
		brr[0] = brr[1];
		brr[1] = temp;
		return brr;
	}

}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值