The problem
Depend what number of arguments a way known as with.
Examples
args_count(1, 2, 3) -> 3
args_count(1, 2, 3, 10) -> 4
The answer in Java code
Some languages check with this because the unfold operator
. In Java, that is known as a VarArg
, which suggests a Variable Quantity of Arguments.
Merely prepend the argument’s identify with three dots (...
) after which check with it like an array of parts.
class Arguments {
public static int countArgs(Object... args) {
return args.size;
}
}
Alternatively, you would additionally use a stream
on it:
import java.util.Arrays;
class Arguments {
public static int countArgs(Object... args) {
return (int) Arrays.stream(args).rely();
}
}
Or loop by means of it utilizing a for loop
:
class Arguments {
public static int countArgs(Object... args) {
int whole = 0;
for (int i = 0; i < args.size; ++i) {
whole++;
}
return whole;
}
}
Take a look at circumstances to validate our resolution
VarArgs
can maintain a number of variable sorts, as illustrated in a few of our take a look at circumstances beneath.
import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.math.BigInteger;
public class SolutionTest {
@Take a look at
public void sampleTest() {
assertEquals(3, Arguments.countArgs(1, 2, 3));
assertEquals(3, Arguments.countArgs(1, 2, "uhsaf uas"));
assertEquals(1, Arguments.countArgs(1));
assertEquals(4, Arguments.countArgs('a', 865, "asfhgajsf", new BigInteger("123456")));
assertEquals(0, Arguments.countArgs());
}
}