I want to create a method along the lines of [return] methodName(int numberOfTimes, String[numberOfTimes] strings)
, meaning that, depending on the value of numberOfChoices
, I can add that number of String
values to the method.
I've wondered and, as I wrote it, it wouldn't work because it would fail at compile time, because numberOfChoices
isn't defined, and, if it would compile, it'd still be tricky to work it out.
I think my best bet is going with String... strings
and do a for loop like this:
void methodName(int numberOfTimes, String... strings) {
for(int i = 0, i < numberOfTimes; i++) {
// do something with strings[i]
}
}
But I still wonder if what I originally wanted was possible.
EDIT: I'm dumb and am always thinking on "sharing" my methods outside of the workspace, that's why I want it to work on the most general way possible. Solution is actually removing numberOfChoices
and just introducing as many String
objects as needed in methodName
. Something along the lines of methodname("One", "Two")
. So, fixed code would be...
void methodName(String... choices) {
for(int i = 0; i < choices.length; i++) {
// do something with choices[i]
}
}