简体   繁体   中英

How to use instanceof in Java?

So I have an arrayList with rooms and im getting the user to put in the room they are looking for, im capturing this as a string and then trying to use instanceOf to match it up with the names of the java classes but cant do this due to comparing a string to a java class.

Also I am capturing there answer in a switch statement to make sure the classes are perfectly spelt and what not. just not sure how to reach in the arrayList and pull out the class they are looking for.

public static void serachRooms(ArrayList<Room> rooms) {
        int option = 0;
        String temp = "";
        boolean flag = false;
        do {
            System.out.println("please Enter What room Type you would like:"
                    + "\nNormal Room = 1"
                    + "\nComputer Room = 2"
                    + "\nBiology Lab = 3"
                    + "\nBoard Room = 4"
                    + "\nYou must choose one!");
            option = input.nextInt();
            if (option == 1 || option == 2 || option == 3 || option == 4) {
                flag = true;
            }
        } while (!flag);
        switch (option) {
            case 1:
                temp = "BiologyLab";
                break;
            case 2:
                temp = "BoardRoom";
                break;
            case 3:
                temp = "ComputerRoom";
                break;
            case 4:
                temp = "Room";
                break;
        }
        for (Room room : rooms) {
            if (temp instanceof BiologyLab) {

            }
        }
    }

instanceof is something pretty special that has to do with types and inheritance . Check out the Java documentation .

For your case, you want to compare the String temp to the String "BiologyLab" . Just use

if ("BiologyLab".equals(temp)) { 
    ...
}

and check out How To Compare Strings In Java for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM