Ludwwwig
Ludwwwig

Reputation: 129

Passing an array of arguments in Java

I started learning Java yesterday and I am now trying to create a program that sums a list of integers in the form of strings. When I try to compile and run the program in Eclipse I get the following error. "The method doSomething(String[]) in the type Calculator is not applicable for the arguments (String, String)". Sorry for that my code looks all messed up. I didn't figure out how to make all of the code in a different font. I got the "inspiration" of trying to pass multiple arguments to a function from the main class since it seems to be working there. I have tried to instead write (String ... arguments) which seems to work fine.

public class Sum {

    int doSomething(String[] arguments) {
        int sum = 0;
        for (int i = 0; i < arguments.length; i++) {
            sum += Integer.parseInt(arguments[i]);

        }
        return sum;

    }

    public static void main(String[] args) {
        String var = "1";
        System.out.print(doSomething("531", var));
    }

}

Upvotes: 0

Views: 129

Answers (3)

DreadHeadedDeveloper
DreadHeadedDeveloper

Reputation: 620

public class Sum {

   static int doSomething(String[] arguments) {
      int sum = 0;
      for (int i = 0; i < arguments.length; i++) {
         sum += Integer.parseInt(arguments[i]);

      }
      return sum;

   }

   public static void main(String[] args) {
      String var = "1";

      String s[] = {"531", var};

      System.out.print(doSomething(s));
   }

}

This way, you have the values stored into an array s , and then you pass that array, problem solved!

Upvotes: 0

injecteer
injecteer

Reputation: 20699

you might want to use this form:

int doSomething(String... arguments) {
    int sum = 0;
    for (int i = 0; i < arguments.length; i++) {
        sum += Integer.parseInt(arguments[i]);
    }
    return sum;
}

then you can call:

doSomething( "aa" );
doSomething( "aa", "bb" );
doSomething();

Upvotes: 1

jhamon
jhamon

Reputation: 3691

You need to initialize a new String array with your values:

doSomething(new String[]{"531", var});

By doing

doSomething("531", var)

You are calling doSomething with 2 String arguments while it's expecting a single argument: String array

Upvotes: 3

Related Questions