I have as an input a String which is a set of numbers with spaces between them, for example:
"30 129 48 29 110 90"
What I want to do is to take that String and input it in an array as integers without firstly using a second array which will store the numbers as Strings. This is what I know how to do:
String line = input.nextLine();
String[] arr = line.split(" ");
int[] array = new int[arr.length];
for (int i = 0; i < arr.length; i++){
array[i] = Integer.parseInt(arr[i]);
}
I want to not make 2 arrays to do the job but in some way to have it done at once in the for loop, I just want it like that because it would be better to my eyes and I like writing clean code which I’ll be able to easily correct later.
EDIT:After jogabonito’s answer this is what I managed to do
Scanner input = new Scanner(System.in);
System.out.printf("Input: ");
StringTokenizer line = new StringTokenizer(input.nextLine());
int[] numbers = new int[line.countTokens()];
for (int i = 0; line.hasMoreTokens(); i++){
numbers[i] = Integer.parseInt((String)line.nextElement());
}
Your current approach is fine, but if you want you “could” do this using StringTokenizer.
Create an int[] of size determined by
countElements(), and then in a while -loop doing anInteger.parseInt(tokenizer.nextElement())Tested code: