java语言使用三种方式实现两个变量的互换用,然后用类封装起来
时间: 2024-05-14 16:17:50 浏览: 14
可以使用以下三种方式实现两个变量的互换:
1. 使用第三个变量进行交换:
```java
public static void swapWithTemp(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
}
```
2. 使用加减法进行交换:
```java
public static void swapWithAddSub(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + ", b = " + b);
}
```
3. 使用异或运算进行交换:
```java
public static void swapWithXor(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a = " + a + ", b = " + b);
}
```
然后,可以将这三个方法封装到一个类中:
```java
public class SwapUtil {
public static void swapWithTemp(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
}
public static void swapWithAddSub(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + ", b = " + b);
}
public static void swapWithXor(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a = " + a + ", b = " + b);
}
}
```
然后就可以在其他地方直接调用 SwapUtil 类中的方法进行变量互换了。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)