Design a method M4
that takes an array A
of doubles and a double value d
, and returns true if d
is not found in A
and false if d
is found in A
Example:
`M49({1.0, 4.5, 7.7, 0.3, 2.1},7.7)`//should return false
Design a method M4
that takes an array A
of doubles and a double value d
, and returns true if d
is not found in A
and false if d
is found in A
Example:
`M49({1.0, 4.5, 7.7, 0.3, 2.1},7.7)`//should return false
You need only a simple notContains
function?
Java 7+:
private boolean notContains(final double[] array, final double n) {
for (double x : array) {
if (x == n) return false;
}
return true;
}
Java 8+ using the Streams API:
private boolean notContains(final double[] array, final double n) {
return Arrays.stream(array).noneMatch(x -> x == n);
}
Usage:
final double[] array = {1.0, 4.5, 7.7, 0.3, 2.1};
System.out.println("Result is: " + notContains(array, 7.7)); // ==> false
System.out.println("Result is: " + notContains(array, 7.2)); // ==> true
Above answer is correct. you can also use variable length arguments(...) for your purpose but one restriction this type of parameter is last in method.
public static boolean notFind(double n,double ...arr){
for(double d:arr){
if(d==n)
return false;
}
return true;
}
And its usages
double[] array = {1.0, 4.5, 7.7, 0.3, 2.1};
System.out.println(notFind(7.7, array)); //false
System.out.println(notFind(7.2, array)); //true