zoukankan      html  css  js  c++  java
  • 不利用临时变量,交换两个变量的值

    不利用临时变量,交换两个变量的值

    Java代码 
    public class ChangeValue 

         
        /** 
         * <不用第三个变量,交换两个变量的值>
         */ 
        public static void main(String[] args) 
        { 
            //方法一  精简,一行代码搞定  
            int x = 3, y = 7, t = 123; 
            System.out.printf("x = %d, y = %d\n", x, y); 
            x = y + 0 * (y = x);  
            System.out.printf("x = %d, y = %d\n", x, y); 
             
            //方法二   简单明了  
            int p = 4, q = 9; 
            System.out.printf("p = %d, q = %d\n", p, q); 
            p = p + q; //7 
            q = p - q; // 7-5=2  q == p 
            p = p - q; //7-2   
            System.out.printf("p = %d, q = %d\n", p, q); 
             
            //方法三  兼容,支持Integer.MAXVALUE的+操作   
            int a = 2, b = 5; 
            System.out.printf("a = %d, b = %d\n", a, b); 
            a ^= b; 
            b ^= a; 
            a ^= b; 
            System.out.printf("a = %d, b = %d\n", a, b); 
             
            //方法四  字符串 数组 
            String s1 = "111", s2 = "222"; 
            System.out.printf("s1 = %s, s2 = %s\n", s1, s2); 
            s1 = s1 + "," + s2; 
            s2 = s1; 
            s1 = s1.split(",")[1]; 
            s2 = s2.split(",")[0]; 
            System.out.printf("s1 = %s, s2 = %s\n", s1, s2); 
             
            //方法五  字符串 表达式(类似方法一) 
            String str1 = "aaa", str2 = "bbb"; 
            System.out.printf("str1 = %s, str2 = %s\n", str1, str2); 
            str1 = str2 + ((str2 = str1) == "" ? "" : ""); 
            System.out.printf("str1 = %s, str2 = %s\n", str1, str2); 
        } 
         
    }

  • 相关阅读:
    T450的Fn lock
    移民,不应该是走投无路后的选择
    门槛低的行业看天赋,门槛高的行业看毅力
    个人是时代的一朵浪花
    转载:XPath基本语法
    爪哇国新游记之三十四----Dom4j的XPath操作
    常去的论坛今天两个传统行业的坛友要下岗了
    异常中要了解的Throwable类中的几个方法
    感觉JVM的默认异常处理不够好,既然不好那我们就自己来处理异常呗!那么如何自己处理异常呢?
    JVM对异常的默认处理方案
  • 原文地址:https://www.cnblogs.com/qiuh/p/2778060.html
Copyright © 2011-2022 走看看