java - Java 如何从一个方法返回多个值

标签 java return-value

我用 Java 编写了一个返回 2 个值的方法。第一个结果计数是 int 类型,第二个是方法是否成功 true/false boolean 类型。 我怎样才能返回这两个值?因此,如果该方法成功,则仅继续。

示例代码:

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

        */
    }

最佳答案

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

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-创建接口(interface)并从要返回值的地方调用抽象方法(您必须在要接收值的类中实现接口(interface)) 希望这会给你前进的粗略想法

关于java - Java 如何从一个方法返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919250/

相关文章:

java - Hibernate 无法实例化抽象类或接口(interface) : java. util.List

java - 在 GUI 中显示文本冒险

java - 在处置监听器中运行作业时出现 IllegalStateException

coldfusion - 不带变量的 CFSET 调用函数

kernel - 我怎样才能从 FreeBSD 系统调用返回 0 以外的东西

c++ - 在引用 C++ 中存储函数的返回值

parameters - 是否有像 n-ary 这样的术语描述返回值的数量而不是函数的参数数量?

java - 如何从 HttpResponse 获取响应正文并使用 Akka HTTP 将其转换为 Java 对象

java - 使用 put/getSerializable 进行 Android 序列化

c - 我怎样才能听到Playsound()'s return value and do someting else if it doesn' t找到.wav