我已经在Java中编写了一个方法,它返回两个值。第一个是结果的计数,类型为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
*/
}
Map.Entry<K,V>
的选项,你可以使用Integer
作为键,Boolean
作为值... - deHaarthrows Exception
来代替具体的异常)。是否有一种“不成功”的方式可以不抛出异常呢? - RealSkepticOptionalInt
,其中失败条件会导致缺少值; (2)使用Integer
,其中null
值表示失败(优先使用OptionalInt,因为它更安全); (3)使用特殊的非有效值,例如当唯一有效值为正数时使用-1; (4)使用某种成对结构,例如Map.Entry
。 - DodgyCodeException