简体   繁体   English

在Java中传递参数数组

[英]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. 我昨天开始学习Java,现在尝试创建一个程序,该程序将字符串形式的整数列表求和。 When I try to compile and run the program in Eclipse I get the following error. 当我尝试在Eclipse中编译并运行程序时,出现以下错误。 "The method doSomething(String[]) in the type Calculator is not applicable for the arguments (String, String)". “计算器类型中的方法doSomething(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. 我试图改为写(String ... arguments)看起来不错。

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

}

You need to initialize a new String array with your values: 您需要使用您的值初始化一个新的String数组:

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 您正在使用2个String参数调用doSomething ,而它只需要一个参数:String数组

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();
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! 这样,您将值存储在数组s ,然后传递该数组,问题已解决!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM