这是我的课程:

房屋详细信息:

private String forename;
private String surname;
private double houseName;
private int numberofHouses;


public CreditCardDetails(String forename, String surname, double houseName, int numberofHouses) {
    this.forename = forename;
    this.surname = surname;
    this.houseName = houseName;
    this.numberofHouses = numberofHouses;
}


房屋购买:

 HashMap <String, HouseDetails> houses = new HashMap<String, HouseDetails>();


这只是一个例子。
我正在尝试查看houseNumber是否首先存在,然后检查houseNumber是否与numberOfHouses相关联。

到目前为止,这是我尝试过的:

public void checkIfHouseMatches(String number ,int numberofHouses){
    for (HouseDetails det : houses.values())
        if (houses.containsKey(number) && det.getNumberofHouses() == numberOfHouses) {
            System.out.println("True");
        }
        else {
        }


但是,如果numberofHouses匹配HashMap中的任何实体,而不是我输入的特定门牌号,则返回true。

我该如何解决?

最佳答案

您的支票错了。

您现在正在执行的操作将检查地图是否包含数字,并且如果任何HouseDetails具有您传递的numberOfHouses,它将返回true

假设您有3个房屋详细信息

HouseDetail1 (number = 1, noOfHouses = 5)
HouseDetail2 (number = 2, noOfHouses = 6)
HouseDetail3 (number = 3, noOfHouses = 5)


并且您搜索了数字1并且noOfHouses = 6
第一次迭代将为false,因为houses.containsKey(number)truedet.getNumberofHouses() == numberOfHousesfalse

第二次迭代都将是true-但这是错误的。将其更改为:

if(houses.containsKey(number)){
     if(houses.get(number).getNumberofHouses() == numberOfHouses){
         System.out.println("True");
     }else{
    }
 }

10-04 17:52