Java 获取返回两个整数的函数
我正在写一个函数,我希望它返回两个整数作为结果。然而,我不能让它这样做。有人能帮我吗?这是我最好的机会Java 获取返回两个整数的函数,java,function,integer,Java,Function,Integer,我正在写一个函数,我希望它返回两个整数作为结果。然而,我不能让它这样做。有人能帮我吗?这是我最好的机会 public static int calc (int s, int b, int c, int d, int g) { if (s==g) return s; else if (s+b==g) return s && b; else if (s + c==g)
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return s;
else if (s+b==g)
return s && b;
else if (s + c==g)
return s && c;
else if (s+d==g)
return s && d;
else
System.out.println("No Answer");
}
您可以让该方法返回一个
int
数组:
public static int[] calc (int s, int b, int c, int d, int g)
你为什么要这样做?如果你有这样的需要,你能不能把你的返回类型改成string,因为在string的情况下,你可以在两个值之间设置分隔符,这将有助于你提取值。。。。比如说10点30分
我同意这是一种错误的解决方法……我假设坚持原始数据类型是有限制的创建一个包含两个整数的小内部类
private static class TwoNumbers {
private Integer a;
private Integer b;
private TwoNumbers(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
您创建一个类的实例并返回它。创建一个“pair”类并返回它
public class Pair<T,Y>
{
public T first;
public Y second;
public Pair(T f, Y s)
{
first = f;
second = s;
}
}
公共类对
{
公共服务优先;
第二,公众参与;
公共对(tf,ys)
{
第一个=f;
秒=秒;
}
}
对于这个特定的问题,因为答案总是返回s
:
....
return s;
....
return s && b;
....
return s && c;
....
return s && d;
....
您可以只返回第二个值。我使用0表示“justs
”,因为第一种情况(if(s==g)
)可以被认为是if(s+0==g)
。如有必要,为此使用不同于0的sentinel值
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return 0;
else if (s+b==g)
return b;
else if (s+c==g)
return c;
else if (s+d==g)
return d;
else {
// System.out.println("No Answer");
// Probably better to throw or return a sentinel value of
// some type rather than print to screen. Which way
// probably depends on whether "no answer" is a normal
// possible condition.
throw new IndexOutOfBoundsException("No Answer");
}
}
如果未引发异常,则s
始终是第一个结果:
try {
int result1 = s;
int result2 = calc(s, b, c, d, g);
} catch (IndexOutOfBoundsException ex) {
System.out.println("No Answer");
}
当只返回
s
时,这不处理这种情况;您应该使用Integer
而不是int
,这样它们就可以为空。请编辑以使用Integer。你们都是对的,我错过了那个案例。另外,请注意,在“无答案”案例中,该方法必须返回一个空的int[]
“has to”?它不能返回null或抛出异常吗?@Gabe-true-但他为什么要调用println?斯蒂芬:他会调用println
,原因可能与他返回s&&g
的原因相同——他只是不知道正确的处理方法。@Gabe在使用集合/数组返回“无结果”时,最好返回空值集合/数组,因为它避免了到处都有空检查。然后,您可以根据返回值的大小/长度以更稳健的方式处理返回值。T
和Y
代表什么?T
和Y
是特定类型的通用占位符。在OPs的情况下,它们都是Integer
T
代表“类型”;V
代表“值”;E
代表“元素”,但我不知道Y
代表什么,我不确定T
在Y
的上下文中代表什么。它们是随机选择的字母,还是代表更长的单词?String
将是我能想到的最糟糕的解决方案。前面提到的对
和int[]
是解决老年退休金问题的恰当方法。