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

我用 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


        */

    }


幕布斯7119047
浏览 229回答 5
5回答

泛舟湖上清波郎朗

有多种方法可以从方法中重新调整多个值,我使用的一些最佳方法是: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- 使用键值对返回 Map3- 制作接口并从要返回值的位置调用抽象方法(您必须在要接收值的类中实现接口)希望这会给您一个粗略的想法前进

慕尼黑的夜晚无繁华

您可以按如下方式创建自定义 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;   }}

潇潇雨雨

我想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 {&nbsp; &nbsp; // I try to analysis the string, but don't want to create a new class&nbsp; &nbsp; var strs = "1,2,ABC,3,4,6,7,1,6,9,XYZ,3,6,3,7,9,2,5,9,ABC";&nbsp; &nbsp; // use any[1] as pointer&nbsp; &nbsp; int[] p_iStrCount = new int[1];&nbsp; &nbsp; // when facing eneric, it's a little different&nbsp; &nbsp; @SuppressWarnings("unchecked") HashMap<Integer, Integer>[] p_hmNum = new HashMap[1];&nbsp; &nbsp; // use pointer as parameters, so I can get multiple results out&nbsp; &nbsp; var hmStr = analysis(strs, p_iStrCount, p_hmNum);&nbsp; &nbsp; var iStrCount = p_iStrCount[0];&nbsp; &nbsp; var hmNum = p_hmNum[0];}// `strs` as input// `pOut_iStrCount`, `pOut_hmNum`, `return` as output// You can ignore the details of this methodstatic HashMap<String, Integer> analysis(@NotNull String strs, @Nullable int[] pOut_iStrCount, @Nullable HashMap<Integer, Integer>[] pOut_hmNum){&nbsp; &nbsp; var aryStr = StringUtils.split(strs, ",");&nbsp; &nbsp; var iStrCount = null != aryStr ? aryStr.length : 0;&nbsp; &nbsp; var hmStr = new HashMap<String, Integer>();&nbsp; &nbsp; var hmNum = new HashMap<Integer, Integer>();&nbsp; &nbsp; if(null != aryStr){&nbsp; &nbsp; &nbsp; &nbsp; for(String str : aryStr){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hmStr.compute(str, (k,v)->(null == v ? 0 : v + 1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int num;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; num = Integer.parseInt(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }catch (NumberFormatException ignore){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hmNum.compute(num, (k,v)->(null == v ? 0 : v + 1));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if(null != pOut_iStrCount){ pOut_iStrCount[1] = iStrCount; }&nbsp; &nbsp; if(null != pOut_hmNum){ pOut_hmNum[1] = hmNum; }&nbsp; &nbsp; return hmStr;}

炎炎设计

我建议坚持您当前的一般方法,而不是尝试从您的方法中返回两条信息。您的方法签名会引发异常,处理此问题的一种可能方法是让您的方法在出现问题时引发异常。否则,这意味着计数查询确实运行了,并且会返回一些计数。但是,您可能应该在 JDBC 代码周围有一个 try catch 块:public static int retrieveData(Connection conn) throws Exception {&nbsp; &nbsp; Statement stmt = null;&nbsp; &nbsp; int totalCount = 0;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; String query = "SELECT COUNT(*) FROM Account";&nbsp; &nbsp; &nbsp; &nbsp; ResultSet rsRetrieve;&nbsp; &nbsp; &nbsp; &nbsp; stmt = conn.createStatement();&nbsp; &nbsp; &nbsp; &nbsp; rsRetrieve = stmt.executeQuery(query);&nbsp; &nbsp; &nbsp; &nbsp; if (rsRetrieve.next()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalCount = rsRetrieve.getInt(1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("totalCount : " + totalCount);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (SQLException e) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; threw new Exception("something went wrong");&nbsp; &nbsp; }&nbsp; &nbsp; finally {&nbsp; &nbsp; &nbsp; &nbsp; if (stmt != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stmt.close();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (conn != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; conn.close();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return totalCount;}所以这里使用的模式是,如果出现问题,则没有计数,调用者会收到异常。否则,如果没有发生异常,则返回一些计数。

繁花不似锦

你不能,但你可以创建一个 bean 类来保存多个对象。如果这是用于程序错误处理,您可能需要查看 Optional (standard) 或 Either (vavr) 来处理多个结果
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java