0

I have 2 classes 'Main' and 'FOR'. From 'Main' I will call method 'display' in class 'FOR'. 'display' will get multiple String values and return it to 'Main' class. Here the returned values must be displayed.

Only one single value is returned. How to get that multiple values returned?

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

Desired output is to return 5 values from the method 'display'. Here I have to get 5 times HI .. But I am getting only one time .. the comment inline explains in more detail.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1443848
  • 177
  • 1
  • 2
  • 11

2 Answers2

2

You can use List.

Example:

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;
}
Pau Kiat Wee
  • 9,485
  • 42
  • 40
0

A slightly different and more complicated approach but is useful in certain situations.

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;
        }
    }
}
tjg184
  • 4,508
  • 1
  • 27
  • 54