标签:包装类 style intval apn 数组 ring 打印 -- public
一.四种方式交换两个数字
1 public class SwapNumbers { 2 public int a; 3 public int b; 4 5 //包装类交换 6 public static void swap (Integer a, Integer b) { 7 Integer temp = a; 8 a = b; 9 b = temp; 10 } 11 12 //直接交换 13 public static void swap (int a, int b) { 14 int temp = a; 15 a = b; 16 b = temp; 17 } 18 19 //数组 20 public static void swap (int[] arr) { 21 int temp = arr[0]; 22 arr[0] = arr[1]; 23 arr[1] = temp; 24 } 25 26 //成员对象 27 public void swapNum(int a, int b) { 28 this.a = b; 29 this.b = a; 30 } 31 32 //包装类打印 33 public static void print(Integer m, Integer n) { 34 System.out.println("m=" + m.intValue() + " n=" + n.intValue()); 35 } 36 //直接打印 37 public static void print(int a, int b) { 38 System.out.println("a=" + a + " b=" + b); 39 } 40 //对象打印 41 public void print() { 42 System.out.println("a=" + this.a + " b=" + this.b); 43 } 44 //数组打印 45 public static void print(int[] a) { 46 for (int i : a) { 47 System.out.print(i + " "); 48 } 49 System.out.println(); 50 } 51 52 53 public static void main(String[] args) { 54 55 System.out.println("------直接交换----------"); 56 int a = 2, b = 3; 57 58 print(a,b); 59 swap(a, b); 60 print(a,b); 61 62 System.out.println("------包装类交换----------"); 63 Integer m = new Integer(2); 64 Integer n = new Integer(3); 65 66 print(m,n); 67 swap(m, n); 68 print(m,n); 69 70 System.out.println("-------数组交换---------"); 71 int[] arr = {2,3}; 72 print(arr); 73 swap(arr); 74 print(arr); 75 76 System.out.println("-------成员变量交换---------"); 77 print(a,b); 78 SwapNumbers sn = new SwapNumbers(); 79 sn.swapNum(a, b); 80 sn.print(); 81 82 } 83 }
结果:
1 ------直接交换---------- 2 a=2 b=3 3 a=2 b=3 4 ------包装类交换---------- 5 m=2 n=3 6 m=2 n=3 7 -------数组交换--------- 8 2 3 9 3 2 10 -------成员变量交换--------- 11 a=2 b=3 12 a=3 b=2
标签:包装类 style intval apn 数组 ring 打印 -- public
原文地址:https://www.cnblogs.com/zhihaospace/p/12217633.html