-12

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
kegs Production
  • 67
  • 1
  • 13
K. Lujan
  • 1
  • 3
  • Did you try anything? or searched for anything? – Ramy M. Mousa Nov 07 '17 at 03:04
  • You can solve your problem by following this SO link. https://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value – Teeloo Nov 07 '17 at 03:05
  • Possible duplicate of [How can I test if an array contains a certain value?](https://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) – 4castle Nov 07 '17 at 03:11
  • Possible duplicate of [Please help me solve my Java homework about arrays](https://stackoverflow.com/q/5502927/3919155) – jotik Nov 15 '17 at 17:04

2 Answers2

2

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
Pedro Rodrigues
  • 1,662
  • 15
  • 19
1

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
Mostch Romi
  • 531
  • 1
  • 6
  • 19