【问题标题】:How to call and declare a method with a variable amount of arguments?如何调用和声明具有可变数量参数的方法?
【发布时间】:2014-11-14 15:30:32
【问题描述】:

我绝望地试图用 (int = amountCoefficients) 数量的参数调用一个函数,并且也用这个数量的参数声明一个函数。

更难的是例如amountCoefficients = 5,那么这意味着有一个由5个块组成的数组,每个块都有一个值(双精度)。所以第一个参数必须等于该数组的第一个块的值,第二个参数必须等于该数组的第二个块的值等等。

事先我们不知道需要多少参数,因为这取决于用户填写的双精度数,因此 amountCoefficients 可能等于 2、4 或任何其他正整数。

我对 Java 还很陌生,我真的不知道该怎么做。正如您在下面看到的,我尝试使用 for 循环做一些事情,但我认为这不起作用。

public class Interpol {

  public static void main(String []args) {

    Scanner scanner = new Scanner(System.in);

        //acquire user input (polynomial coefficients and interval values x1 and x2)
        ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
        int amountCoefficients = 0;
        while (scanner.hasNextDouble()) {
            polynomialCoefficients.add(scanner.nextDouble());
            amountCoefficients++;
        }
        String in = scanner.next();
        double x1 = scanner.nextDouble();
        double x2 = scanner.nextDouble();

        //call method f to determine the polynomial function
        int i = 0;
        for (i = 0; i < amountCoefficients; i++) {
        f
        }

        //call method findaroot to determine the root


        //print result

  }

}

public static double f(double x) {
//function of which a root is to be found
}

【问题讨论】:

    标签: java arrays variables methods


    【解决方案1】:

    您可以创建一个采用列表或数组的方法。然后该方法可以使用 List.size() 和 array.length 来处理每个对象。

    public static void main(String[] args){
        ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
    
        // get data
        ...
    
        process(polynomialCoefficients);
    }
    
    public void process(List<Double> coefficients){
        for(int i = 0; i < coefficients.size(); i ++){
            System.out.println("Element " + i + ": " + coefficients.get(i));
        }
    }
    

    【讨论】:

    • 感谢您的解决方案!
    【解决方案2】:

    您可以使用VarArgs notation 接收任意数量的参数,尽管它们将被转换为array。这是通过如下代码实现的:

    public void printOneEachLine(String... parameters) {
       for (String parameter : parameters) {
          System.out.println(parameter);
       }
    }
    

    你可以这样称呼它:

    printOneEachLine("msg1", "msg2");
    printOneEachLine("msg3", "msg4", "msg5", "msg6");
    

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多