java:从方法返回多个值

时间:2012-09-29 07:30:55

标签: java

  

可能重复:
  How to return multiple objects from a Java method?

假设N = a + b; 对于数字N,我想生成所有可能的值a和b。喜欢 如果N = 7 a且b为(1 + 6),(2 + 5),(3 + 4)。

我已经用一种方法编写了这个逻辑。

static void sumofNum(int N){

        for(int a=1; a<N; a++){
                //a+b=N
                int b = N-a;
                System.out.println(a+","+b);
                int next =a+1;
                if(next==b | a==b)
                    return;
        }   
    }

我想从这种方法返回(1,6),(2,5),(3,4)。对于任何N,接下来可以有更多(a,b)组合从此方法返回。

4 个答案:

答案 0 :(得分:3)

返回List<String>(假设"(1,6)"将存储为String)。使用List的其中一个实现(例如ArrayList)来构建列表:

static List<String> sumofNum(int N)
{
    List<String> result = new ArrayList<String>();

    for(int a=1; a<N; a++)
    {
        int b = N-a;
        result.add("(" + a + "," + b + ")");
        int next =a+1;
        if(next==b || a==b)
            return result;
    }   
    return result;
}

答案 1 :(得分:1)

如果要将它们作为整数返回,请定义一个包含两个整数的对象(或我在下面所做的滥用点)并返回这些对象的列表。如果您定义自己的对象,只需将point替换为。

static ArrayList<Point> sumofNum(int N){
    ArrayList<Point> result = new ArrayList<Point>();
    for(int a=1; a<N; a++){
            //a+b=N
            int b = N-a;
        System.out.println(a+","+b);
        int next =a+1;
        if(next==b | a==b)
           result.add(new Point(a,b));
        }   
    return result;
    }

您可以使用以下列表从列表中获取结果:

results = sumofNum(7);
int a = results.get(0).x; //a = 1
int b = results.get(0).y; //b = 6

答案 2 :(得分:1)

在面向对象(也是功能)的编程风格中,您可以将结果传递给使用者,以避免将结果存储在集合或列表中。

示例:

static void sumofNum(int N){
  for (int a=1; a<N; a++){
    //a+b=N
    int b = N-a;
    consumer.consume(a,b);
    int next =a+1;
    if (next==b || a==b)
      return;
    }   
}

[代码的进一步改进是可能的(例如,避免内部if和return),...]

答案 3 :(得分:0)

Consider the nos as (1,6),(2,5),(3,4)

- 现在返回ArrayList<String>,其中包含String格式中的每个值为“1,6”,“2,5”,“3,4”。< / p>

- 当您收到返回的ArrayList时,请使用split()方法","作为分隔符,以获得“1,6”中的1和6等等....

相关问题