arraylist—在java中,如何将列表(或数组)中未知数量的变量动态插入到方法参数中?

klr1opcd  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(370)

例子:

public class Example {
  public int doMath(String name, int... a) {
    System.out.println("My name is " + name);
    for (int i: a)
      int b = a+a
    return (b);
  }
  public static void main(String args[]){
    int[] testArray = new int[]{1,2,3}; //In this case size of the array is 3.
                                        // Could be any number during runtime.

    doMath(test[0],test[1],test[2]); //Need to insert values from into the doMath argument,
                                     // dynamically because
                                     // will not know length of array
                                     // during compile time
  }
}

我有一个包含对象的列表/数组,我将要插入这些值的方法包含一个vararg参数。我需要动态地将这些值插入到这个方法中,而不必硬编码列表的大小。因为在运行时,用户输入可以在0到100之间的任何地方变化。我需要能够将这个列表中的值插入到这个方法中,插入到正确的位置。

eivgtgni

eivgtgni1#

你的代码有一些问题。。。
不能从静态方法调用非静态方法。
不能声明局部变量(在循环内)并在范围外返回它。它的编译时错误。
当您只使用数组时,不需要varargs。当您可能有一个元素数组或单个元素时,需要varargs。

public class Example {

    // the main method can call this method
    public static int doMath(String name, int[] a) {
        System.out.println("My name is " + name);
        int b = 0;
        for (int i : a)
            b = b + i;
        return b;
    }

    public static void main(String args[]) {

        while (condition) { // just for example with a dynamic array.
            int size = 10; // you might ask user for the size of the array

            int[] array = new int[size];
            for (int index = 0; index < size; index++)
                array[index] = index * 2; // you might ask user for input
            int result = doMath("math", array);
            System.out.println(result);
        }
    }
}

相关问题