zoukankan      html  css  js  c++  java
  • 在Java中返回多个值

    [
  •   Java 方法

    在Java中返回多个值

    Java不支持多值返回。但是我们可以使用以下解决方案来返回多个值。

    如果所有返回的元素都是相同类型的

    我们可以用Java返回一个数组。下面是一个展示相同的Java程序。

    // A Java program to demonstrate that a method
    // can return multiple values of same type by
    // returning an array
    class Test
    {
        // Returns an array such that first element
        // of array is a+b, and second element is a-b
        static int[] getSumAndSub(int a, int b)
        {
            int[] ans = new int[2];
            ans[0] = a + b;
            ans[1] = a - b;
    
            // returning array of elements
            return ans;
        }
    
        // Driver method
        public static void main(String[] args)
        {
            int[] ans = getSumAndSub(100,50);
            System.out.println("Sum = " + ans[0]);
            System.out.println("Sub = " + ans[1]);
        }
    }
    

    上述代码的输出将是:

    Sum = 150
    Sub = 50

     

    如果返回的元素是不同类型的

    我们可以将所有返回的类型封装到一个类中,然后返回该类的一个对象。让我们看看下面的代码。

    // A Java program to demonstrate that we can return
    // multiple values of different types by making a class
    // and returning an object of class.
    
    // A class that is used to store and return
    // two members of different types
    class MultiDiv
    {
        int mul;    // To store multiplication
        double div; // To store division
        MultiDiv(int m, double d)
        {
            mul = m;
            div = d;
        }
    }
    
    class Test
    {
        static MultiDiv getMultandDiv(int a, int b)
        {
            // Returning multiple values of different
            // types by returning an object
            return new MultiDiv(a*b, (double)a/b);
        }
    
        // Driver code
        public static void main(String[] args)
        {
            MultiDiv ans = getMultandDiv(10, 20);
            System.out.println("Multiplication = " + ans.mul);
            System.out.println("Division = " + ans.div);
        }
    }
    

    输出:

     Multiplication = 200
    Division = 0.5
  •   Java 方法
    ]
    转载请保留页面地址:https://www.breakyizhan.com/java/4112.html
  • 相关阅读:
    装箱与拆箱
    java中final的用法
    一次坑爹的Oracle in查询
    Spring-Security-Oauth整合Spring-Security,拦截器
    jvisualvm连接远程Tomcat
    7.Spring-Cloud服务容错保护之Hystrix初探
    8.Spring-Cloud-Hystrix之异常处理
    9.Spring-Cloud-Hystrix之请求缓存(踩坑)
    10.Spring-Cloud-Hystrix之熔断监控Hystrix Dashboard单个应用
    11.Spring-Cloud-Hystrix之熔断监控Turbine
  • 原文地址:https://www.cnblogs.com/breakyizhan/p/13263088.html
Copyright © 2011-2022 走看看