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

How to use instanceof with multiple object parameters?

Error Message: Incompatible conditional operand types BM[] and SM

public void count(BM... bm) {

        int countSM = 0;
        int countKM = 0;

        System.out.println(bm.length);

        if (bm instanceof SM) {
            System.out.println("Von SM");
            countSM++;
            System.out.println(countSM);
        } else if (bm instanceof KM) {
            System.out.println("Von KM");
            countKM++;
            System.out.println(countKM);
        }

    }

I want to count and print out, how many objects of this specific class are in the parameter

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

>Solution :

Try this:

public void count(BM... bm) {

    int countSM = 0;
    int countKM = 0;

    System.out.println(bm.length);
    for(BM bm_object : bm)
        if (bm_object instanceof SM) {
            System.out.println("Von SM");
            countSM++;
            System.out.println(countSM);
        } else if (bm_object instanceof KM) {
            System.out.println("Von KM");
            countKM++;
            System.out.println(countKM);
        }

    }
}
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