0

「メイン」と「FOR」の2つのクラスがあります。「Main」から、クラス「FOR」のメソッド「display」を呼び出します。「display」は複数の文字列値を取得し、「Main」クラスに返します。ここで、返された値を表示する必要があります。

1 つの値のみが返されます。複数の値が返されるようにするにはどうすればよいですか?

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

授業のために

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 つの値を返すことです。ここでは、HI を 5 回取得する必要があります。

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 に答える