Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i loop through parameter variables passed by function in java

This is my initial code,

public class Main {
    public static void main(String[] args) {

//   --------Declaring variables--------
        int arrLength = 6;
        String[] arr1 = new String[arrLength];
        String[] arr2 = new String[arrLength];
        String[] arr3 = new String[arrLength];
        
        joinArrays(arr1,arr2,arr3);
}

private static void joinArrays(String[] arr1, String[] arr2, String[] arr3){
        System.out.print("Array 1 : ");
        System.out.println(String.join(",",arr1));
        System.out.println("");

        System.out.print("Array 2 : ");
        System.out.println(String.join(",",arr2));
        System.out.println("");

        System.out.print("Array 3 : ");
        System.out.println(String.join(",",arr3));
        System.out.println("");

    }

But i need to do this in a loop (without using so much print methods).
I tried below way, but it only print out

Array 1 : arr1
Array 2 : arr2 

likewise, it doesn’t join the list that passed to the parameter.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private static void joinArrays(String[] arr1, String[] arr2, String[] arr3){
        for(int i = 0; i<3;i++){
          System.out.print("Array "+i+" : ");
          System.out.println(String.join(",","arr"+i));
          System.out.println("");
   }
}

How can i do this looping thing easy.

>Solution :

There is no (easy) way to iterate through the arguments passed to a method in Java.

If you want to prevent repeating yourself, then you can put the code in a separate method, and call that with the argument variables one at a time:

private static void joinArrays(String[] arr1, String[] arr2, String[] arr3) {
    joinArray("Array 1 : ", arr1);
    joinArray("Array 2 : ", arr2);
    joinArray("Array 3 : ", arr3);
}

private static void joinArray(String label, String[] arr) {
    System.out.print(label);
    System.out.println(String.join(",", arr));
    System.out.println("");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading