Is there a way to make an array in java, without defining or asking for it’s length first ? A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.
目前尚不清楚您所处的状态.如果您知道执行时而不是编译时的数组长度,那就可以了:
public class Test {
public static void main(String[] args) {
int length = Integer.parseInt(args[0]);
String[] array = new String[length];
System.out.println("Created an array of length: " + array.length);
}
}
您可以将其运行为:
java Test 5
它将创建一个长度为5的数组.
如果在创建之前确实不知道数组的长度,例如,如果您要询问用户元素,然后在完成时让他们输入一些特殊值,那么您可能想要使用某种列表,例如ArrayList.
例如:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers, with 0 to end");
List list = new ArrayList<>();
while (true) {
int input = scanner.nextInt();
if (input == 0) {
break;
}
list.add(input);
}
System.out.println("You entered: " + list);
}
}
然后,如果确实需要,可以将该列表转换为数组,但理想情况下,可以继续将其用作列表.