Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot convert double to boolean

Apologies if this is confusing, I’m still new to coding. I’m trying to prompt the user for a number and display if the number entered is or is not in the array. Can’t really seem to find an answer.

import java.util.Scanner;

public class Arrays3 {
    public static void main(String[] args) {
        double[] don = { 2.1, 3.2, 4.5, 6.0, 4.5, 1.5, 6.0, 7.0, 6.0, 9.0 };
        Scanner kbd = new Scanner(System.in);

        System.out.println("Enter a number");
        double num = kbd.nextDouble();
        if (num = don.length) {
            System.out.println("The number you entered is in the Array");
        } else {
            System.out.println("The number you entered is not in the Array");
        }

    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you are searching for the input value inside your data array, you may want to traverse the array and check if the input matches with any value inside the array.

public static void main(String[] args) {
    double[] don = { 2.1, 3.2, 4.5, 6.0, 4.5, 1.5, 6.0, 7.0, 6.0, 9.0 };
    Scanner kbd = new Scanner(System.in);

    System.out.println("Enter a number");
    double num = kbd.nextDouble();
    boolean isFound = false;

    for(int i = 0; i < don.length; i++) {
        if (num == don[i]) {
            isFound = true;
        }
    }

    if (isFound) {
        System.out.println("The number you entered is in the Array");
    } else {
        System.out.println("The number you entered is not in the Array");
    }
}

There are few ways to check if the element exists in the array

  • Using a for-loop
  • Java 8 Stream API
  • Arrays.asList().contains()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading