我无可救药地尝试使用 (int = amountCoefficients) 数量的参数调用函数,并也声明具有该数量参数的函数。
让事情变得更困难的是,例如 amountCoefficients = 5,那么这意味着有一个由 5 个 block 组成的数组,每个 block 都有一个值( double )。因此,第一个参数必须等于该数组的第一个 block 的值,第二个参数必须等于该数组的第二个 block 的值,依此类推。
事先我们不知道需要多少个参数,因为这取决于用户填写的 double 数量,因此 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
}
最佳答案
您可以创建一个采用列表或数组的方法。然后该方法可以使用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));
}
}
关于java - 如何调用和声明具有可变数量参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944044/