Home > Back-end >  How to use instanceof with multiple object parameters?
How to use instanceof with multiple object parameters?

Time:01-26

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

CodePudding user response:

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

    }
}
  •  Tags:  
  • Related