为了账号安全,请及时绑定邮箱和手机立即绑定

如何从Java中的方法返回多个值

如何从Java中的方法返回多个值

幕布斯7119047 2022-11-02 15:18:28
我用 Java 编写了一个返回 2 个值的方法。第一个结果计数是 int 类型,如果方法是成功 true/false 布尔类型,则为第二个。如何返回两个值?因此,如果该方法成功,则仅继续。示例代码:public static void main(String args[]){    int count = 0;    boolean status = false;    //count = retrieveData(); Current code working but captures only 1 values at a time i.e. Count not the status    /* Expected Code    if (status == true)  // where status and count is returned from retrieveData method    {        count = retrieveData();        System.out.println("Status is true so can proceed");    }    else        System.out.println("Status is not true so don't proceed");    */}public static int retrieveData() throws  Exception     {        boolean success = false;        String query = "SELECT Count(1) FROM Account";        int totalCount=0;        ResultSet rsRetrieve = null;            Statement stmt = null;            stmt = conn.createStatement();            rsRetrieve = stmt.executeQuery(query);            while (rsRetrieve.next())            {                totalCount= rsRetrieve.getInt(1);                System.out.println("totalCount : "+totalCount);            }        success = true;        return totalCount; // current working code but returns only 1 value i.e. Count not status        /*   Expected        return success + totalCount        */    }
查看完整描述

5 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

有多种方法可以从方法中重新调整多个值,我使用的一些最佳方法是:


1-为要返回的数据类型创建类,例如,您要返回两个字符串,使类如下所示:


public class myType {

            String a;

            String b;


            public String getA() {

                return a;

            }


            public void setA(String _a) {

                a = _a;

            }

            //And All other geter setters

        }

并将您的方法的返回类型设置为上述类。


2- 使用键值对返回 Map

3- 制作接口并从要返回值的位置调用抽象方法(您必须在要接收值的类中实现接口)希望这会给您一个粗略的想法前进


查看完整回答
反对 回复 2022-11-02
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

您可以按如下方式创建自定义 java 对象


public class Result {


   private boolean success;

   private int totalResults;


   public Result(boolean success, int totalResults){

    this.success = success;

    this.totalResults = totalResults;

   }

   public boolean getSuccess(){

     return this.success;

   }


   public boolean getTotalResults(){

       return this.totalResults;

   }


}


查看完整回答
反对 回复 2022-11-02
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

我想any[1]用来模拟指针。像 C++*p和 C# out。


boolean[] p_status = new boolean[1];

int count = retrieveData(p_status);

boolean status = p_status[0];

其他样品,能量:


public static void main(String[] args) throws JsonProcessingException {

    // I try to analysis the string, but don't want to create a new class

    var strs = "1,2,ABC,3,4,6,7,1,6,9,XYZ,3,6,3,7,9,2,5,9,ABC";


    // use any[1] as pointer

    int[] p_iStrCount = new int[1];

    // when facing eneric, it's a little different

    @SuppressWarnings("unchecked") HashMap<Integer, Integer>[] p_hmNum = new HashMap[1];


    // use pointer as parameters, so I can get multiple results out

    var hmStr = analysis(strs, p_iStrCount, p_hmNum);

    var iStrCount = p_iStrCount[0];

    var hmNum = p_hmNum[0];

}


// `strs` as input

// `pOut_iStrCount`, `pOut_hmNum`, `return` as output

// You can ignore the details of this method

static HashMap<String, Integer> analysis(@NotNull String strs, @Nullable int[] pOut_iStrCount, @Nullable HashMap<Integer, Integer>[] pOut_hmNum){


    var aryStr = StringUtils.split(strs, ",");

    var iStrCount = null != aryStr ? aryStr.length : 0;

    var hmStr = new HashMap<String, Integer>();

    var hmNum = new HashMap<Integer, Integer>();


    if(null != aryStr){

        for(String str : aryStr){

            hmStr.compute(str, (k,v)->(null == v ? 0 : v + 1));

            int num;

            try{

                num = Integer.parseInt(str);

            }catch (NumberFormatException ignore){

                continue;

            }

            hmNum.compute(num, (k,v)->(null == v ? 0 : v + 1));

        }

    }


    if(null != pOut_iStrCount){ pOut_iStrCount[1] = iStrCount; }

    if(null != pOut_hmNum){ pOut_hmNum[1] = hmNum; }


    return hmStr;

}


查看完整回答
反对 回复 2022-11-02
?
炎炎设计

TA贡献1808条经验 获得超4个赞

我建议坚持您当前的一般方法,而不是尝试从您的方法中返回两条信息。您的方法签名会引发异常,处理此问题的一种可能方法是让您的方法在出现问题时引发异常。否则,这意味着计数查询确实运行了,并且会返回一些计数。但是,您可能应该在 JDBC 代码周围有一个 try catch 块:


public static int retrieveData(Connection conn) throws Exception {

    Statement stmt = null;

    int totalCount = 0;


    try {

        String query = "SELECT COUNT(*) FROM Account";


        ResultSet rsRetrieve;

        stmt = conn.createStatement();

        rsRetrieve = stmt.executeQuery(query);


        if (rsRetrieve.next()) {

            totalCount = rsRetrieve.getInt(1);

            System.out.println("totalCount : " + totalCount);

        }

    }

    catch (SQLException e) {

        System.out.println(e.getMessage());

        threw new Exception("something went wrong");

    }

    finally {

        if (stmt != null) {

            stmt.close();

        }


        if (conn != null) {

            conn.close();

        }


    }


    return totalCount;

}

所以这里使用的模式是,如果出现问题,则没有计数,调用者会收到异常。否则,如果没有发生异常,则返回一些计数。


查看完整回答
反对 回复 2022-11-02
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

你不能,但你可以创建一个 bean 类来保存多个对象。

如果这是用于程序错误处理,您可能需要查看 Optional (standard) 或 Either (vavr) 来处理多个结果


查看完整回答
反对 回复 2022-11-02
  • 5 回答
  • 0 关注
  • 228 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号