CursedChico
CursedChico

Reputation: 581

Java invoking a method with array parameter

I wrote the following function:

public void enterlessonnames(String[] names)
        {
            String msg="";

            for (int i=0;i<names.length;i++)
            {

                msg=msg+names[i];
            }

            System.out.println(msg);
 }

I want to call like that, giving the input:

enterlessonnames({"math","art"} );

How can i call this in main?

enterlessonnames(names[{"math","art"} ]);

It does not any of them.

Multiple markers at this line:

- Syntax error, insert ")" to complete MethodInvocation
- Syntax error on token ",", delete this token
- Syntax error, insert ";" to complete Statement
- Syntax error on tokens, delete these tokens

Upvotes: 4

Views: 177

Answers (5)

reto
reto

Reputation: 10463

You need to create a proper String array instance, something like this:

String[] array = new String[]{"math", "art"};

Your fixed call would be:

enterlessonnames( new String[]{"math", "art"} );

or

String[] lessons = new String[]{"math", "art"};
enterlessonnames(lessons);

Upvotes: 3

gterdem
gterdem

Reputation: 842

Probably what you are looking for is invoking like this:

enterlessonnames(new String[] {"CursedChico","Science","Maths"});

Keep in mind that newly created array will be disposed and won't be available to re-use in an other method.

If you are not enforced, I can suggest you to use generics like;

List<String> names= new ArrayList<String>();
names.add("Math");
names.add("Science");

etc..

And you can modify your method as;

public void enterLessonNames(List<String> names)    
{
   Here goes your code;
}

Afterwards invoking;

enterLessonNames(names);

Hope it helps.

Upvotes: 1

rahulserver
rahulserver

Reputation: 11205

Call it as:

public class ArrayCaller{
    public static void main(final String[] args) {
        new ArrayCaller().enterlessonnames(new String[]{"lesson1", "lesson2", "lesson3"});
    }

    public void  enterlessonnames(String[] names) {
        String msg="";

        for (int i=0;i<names.length;i++) {
            msg=msg+names[i];
        }
        System.out.println(msg);
    }
}

Cheers!!

Upvotes: 1

NickJ
NickJ

Reputation: 9579

In addition to the other answers, you could declare your method like this:

public void  enterlessonnames(String... names) {
  //do stuff
}

Then it can be called like this:

enterlessonnames( new String[] { "a", "b" } );

or like this:

enterlessonnames("just one string!");

or like this:

enterlessonnames("one string", "another string");  //as many strings as you like

Upvotes: 2

yair
yair

Reputation: 9255

like this:

enterlessonnames( new String[] { "a", "b" } );

FYI, java naming conventions imply that method names have first letter of each word in the name start with a capital letter except for the first word that starts with non-capital. In your case: enterLessonNames.

Upvotes: 3

Related Questions