Requirements:
Interchange Two-digit Value
Method One: with Third-party variables
/*** Two values are interchanged with third-party variables *@authorAdministration **/ public classExchangevalue { public Static voidmain (string[] Args) {intA = 10; intb = 15; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); System.out.println ("perform an interchange operation on two values ..."); inttemp =a; A=b; b=temp; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); }}
Operation Result:
Value of a: ten, b value: Two to perform an interchange operation ... a value: 10, value of b
Method Two: no need for Third-party variables (plus and minus OPERATIONS)
/*** No need to use Third-party variables to swap two of values *@authorAdministration **/ public classExchangevalue { public Static voidmain (string[] Args) {intA = 10; intb = 15; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); System.out.println ("perform an interchange operation on two values ..."); A=a+b; b=a-b; A=a-b; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); }}
Operation Result:
Value of a: ten, b value: Two to perform an interchange operation ... a value: 10, value of b
Method three: no need for Third-party variables (xor or Operation)
/*** No need to use Third-party variables to swap two of values *@authorAdministration **/ public classExchangevalue { public Static voidmain (string[] Args) {intA = 10; intb = 15; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); System.out.println ("perform an interchange operation on two values ..."); A=a^b; b=a^b; A=a^b; System.out.println ("a's value:" +a+ ", The value of \tb:" +b); }}
principle: a value A and a value B are different or the operation gets c, then the C and B operations can be restored A. So this principle can be used to achieve the exchange of two Values.
Operation Result:
Value of a: ten, b value: Two to perform an interchange operation ... a value: 10, value of b
Java small case--three ways to exchange two values