0

我有 2 个课程“主要”和“FOR”。从“Main”中,我将在“FOR”类中调用方法“display”。'display' 将获取多个 String 值并将其返回给 'Main' 类。此处必须显示返回值。

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

主类

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);
        }
    }

上课

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;
        }
}

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

4

2 回答 2

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;
}
于 2012-06-16T11:32:32.220 回答
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;
        }
    }
}
于 2012-06-16T11:38:50.613 回答