PietroSupport
PietroSupport

Reputation: 19

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

Upvotes: 1

Views: 219

Answers (1)

Aditya Arora
Aditya Arora

Reputation: 203

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

    }
}

Upvotes: 1

Related Questions