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.
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.
It's unclear exactly what situation you're in. If you know the array length at execution time but not at compile time, that's fine:
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);
}
}
You can run that as:
java Test 5
and it will create an array of length 5.
If you really don't know the length of the array before you need to create it - for example, if you're going to ask the user for elements, and then get them to enter some special value when they're done, then you would probably want to use a List
of some kind, such as ArrayList
.
For example:
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<Integer> list = new ArrayList<>();
while (true) {
int input = scanner.nextInt();
if (input == 0) {
break;
}
list.add(input);
}
System.out.println("You entered: " + list);
}
}
You can then convert that List
into an array if you really need to, but ideally you can just keep using it as a List
.
See more on this question at Stackoverflow