如何将多个时间值返回给java中的类?

时间:2012-06-16 11:29:48

标签: java for-loop return-value

我有2个班级'Main'和'FOR'。从'Main'我将在'FOR'类中调用方法'display'。 'display'将获得多个String值并将其返回到'Main'类。这里必须显示返回的值。

仅返回一个值。如何获得多个值?

Main.class

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FOR obj = new FOR();
            String str = obj.display();
        System.out.print(str);
        }
    }

FOR.class

public class FOR {
    int j=5;
    String hi="hi";
    String display()
    {
        for(int i=0;i<j;i++)
        {
        System.out.print(hi);
//   If I use this I will get 5 times hi.. but I dont 
///  want like this. I have to return hi String 5times to main and I have to display
///  but should not call 5 times display() too,by calling one time, I have to return 
///  5 time a string to Main class


        }
        return hi;
        }
}

所需的输出是从方法'display'返回5个值。在这里,我必须得到5次HI ..但我只得到一次..评论内联更详细地解释。

2 个答案:

答案 0 :(得分:2)

您可以使用List

示例:

import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FOR obj=new FOR();
        List<String> str= obj.display();
        for(String v: str) {
            System.out.print(v);
        }

    }
}


import java.util.List;
import java.util.ArrayList;
List<String> display() {   
    int j=5;
    String hi="hi";

    List<String> result = new ArrayList<String>();

    for(int i=0;i<j;i++) {
        result.add(hi);         
    }
    return result;
}

答案 1 :(得分:0)

稍微不同且更复杂的方法,但在某些情况下很有用。

public class Main {
    public static void main(String[] args) {
        FOR obj = new FOR();
        String str = obj.display(new ICallback() {

            @Override
            public void doSomething(String obj) {
                // do whatever you want with this
                System.out.println("This is being returned for each execution " + obj);
            }
        });

        System.out.print(str);
    }

    public static interface ICallback
    {
        void doSomething(String obj);
    }

    public static class FOR {
        int j = 5;
        String hi = "hi";

        String display(ICallback callback) {
            for (int i = 0; i < j; i++) {
                callback.doSomething(hi);
            }
            return hi;
        }
    }
}