Home > Mobile >  How do I pass an array of strings as a parameter to a class object?
How do I pass an array of strings as a parameter to a class object?

Time:04-22

Instead of a single parameter, I tried passing arrays as parameter and this happens. Where am I going wrong? I am a beginner, Btw!

public class ClassArrayTest
{
    public static void main(String[] args)
    {
        fruit f = new fruit({"peach","apple","mango"});
        f.display();

    }
}



class fruit
{
    String[] a;
    
    public fruit(String[] aa)
    {
        a = aa;
    }
    
    void display()
    {
        System.out.println(a);
    }
}

CodePudding user response:

public class ClassArrayTest {

    public static void main(String... args) {
       fruit f = new fruit(new String []{"peach","apple","mango"}); // use new Sring[]{""...} when passing an array
        f.display();
    }

}

class fruit
{
    String[] a;
    
    public fruit(String[] aa)
    {
        a = aa;
    }
    
    void display()
    {
        for(String stringElements : a){
        System.out.println(stringElements );
        }// i also find it easy to iterate through than print an object
        
    }
}

CodePudding user response:

import java.util.Arrays;

public class ClassArrayTest {
    
public static void main(String[] args) {
            fruit f = new fruit(new String[] { "A", "B", "C" });
            f.display();
        }
    }

class fruit {

    String[] a;

    public fruit(String[] aa) {
        a = aa;
    }

    void display() {
        Arrays.stream(a).forEach(System.out::println);
    }
}

CodePudding user response:

Is this what you want?

public class ClassArrayTest
{
    public static void main(String[] args)
    {
        String[] aa = {"peach","apple","mango"};
        fruit f = new fruit(aa);
        f.display();

    }
}


class fruit
{
    String[] a;
    
    public fruit(String[] aa)
    {
        a = aa;
    }
    
    void display()
    {
        // System.out.println(a);
        for (String f: a) {
            System.out.println(f);
        }
    }
}

And I suggest that use Fruit rather than fruit to name a class in Java.

CodePudding user response:

OK ... so I think your problem is understanding the syntax of creating initialized arrays in Java. The {"peach","apple","mango"} syntax can only be used in two contexts:

String[] fruit = {"peach", "apple", "mango"};

or

new String[]{"peach", "apple", "mango"};

You were trying to use it like this:

someMethod({"peach", "apple", "mango"});

but that is not permitted. The { ... } syntax cannot be used there. But you could write this:

someMethod(new String[]{"peach", "apple", "mango"});
  • Related