zoukankan      html  css  js  c++  java
  • java中两个值互换

    两个值互换有以下三种方式:

    1. 使用临时变量(此种方法便于理解)
      1 x = 10;
      2 y = 20;
      3 //begin
      4 int temp = x;
      5 x = y;
      6 y = temp;
      7 //end;
      8 //此时x = 20; y = 10;
      View Code
    2. 利用加减来实现(此种方法只适应于数值比较小的情况,如果数值较大,会超界)
      1 x = 10;
      2 y = 20;
      3 //begin
      4 x = x + y ;
      5 y = x - y;
      6 x = x - y;
      7 //end;
      8 //此时x = 20; y = 10;
      View Code 
    3. 利用位运算实现(不用考虑数值大小问题)
      1 x = 10;
      2 y = 20;
      3 //begin
      4 x = x ^ y;
      5 y = x ^ y;
      6 x = x ^ y;
      7 //end;
      8 //此时x = 20; y = 10;
      View Code

    但是java中没有指针的概念,如果要把两值互换封装起来的话,那么形参只能是传入对象,不能直接传入数值,因为传入数值不能改变原来的值;也没有C#中的ref关键字。

    • 直接在程序中写
    • 函数调用,这种方法可能比较麻烦,没有直接用上面的方便,但是也是一种思路;
       1 package com.test;
       2 public class test1 {
       3     public static void main(String[] args) {
       4         int x = 10;
       5         int y = 20;
       6         int[] tempArr = swap(x,y);//定义数组接收返回值
       7         x = tempArr[0];
       8         y = tempArr[1];
       9         System.out.println("x="+x+";y="+y);
      10     }
      11     public static int[] swap(int x, int y)//定义函数换值,返回数组
      12     {
      13         int[] arr = new int [2];
      14         x = x ^ y;
      15         y = x ^ y;
      16         x = x ^ y;
      17         arr[0] = x;
      18         arr[1] = y;
      19         return arr;
      20         
      21     }
      22 }
      View Code
  • 相关阅读:
    Deepin安装Python开发环境
    Deepin怎样安装C/C++编译环境更好
    当 tcpdump -w 遇到 Permission denied
    c++中的虚函数
    c++中的new 和delete
    ubuntu没有输入窗口,不能调用输入法
    Ubuntu下升级VisualBox后无法启动 Kernel driver not installed (rc=-1908)
    BCD与GRUB
    adb shell device not found解决
    unsupported number of arguments...的错误
  • 原文地址:https://www.cnblogs.com/csschn/p/5065769.html
Copyright © 2011-2022 走看看