Правильный способ печати объектов из ArrayList в рамках критериев

#java

#java

Вопрос:

Я постараюсь изо всех сил объяснить, что я пытаюсь сделать. Во-первых, вот мои классы:

Класс HouseListTester

     package RealEstateListings;
import java.util.*;

public class HouseListTester {
    
    public static void main(String[] args) {
        //create scanner for user input via console
        Scanner input = new Scanner(System.in);
        
        
        System.out.println("Welcome to Mike's House Listing");
        System.out.println("Please enter the file name of the house list: ");
        String sourceFolder = "C:\Users\micha\Documents\eclipse-workspace\Real Estate Listings\src\RealEstateListings\";
        HouseList fileName = new HouseList(sourceFolder input.next());
        
        System.out.println();
        
        System.out.println("Please enter your search criteria");
        
        System.out.print("Minimum price: ");
        int minPrice = input.nextInt();
        System.out.print("Maximum price: ");
        int maxPrice = input.nextInt();
        System.out.print("Minimum area: ");
        int minArea = input.nextInt();
        System.out.print("Maximum area: ");
        int maxArea = input.nextInt();
        System.out.print("Minimum number of bedrooms: ");
        int minBedrooms = input.nextInt();
        System.out.print("Maximum number of bedrooms: ");
        int maxBedrooms = input.nextInt();
        
        Criteria userCriteria = new Criteria(minPrice, maxPrice, minArea, maxArea, minBedrooms, maxBedrooms);
        
        fileName.printHouses(userCriteria); 
    }
}
  

Класс HouseList

 
    package RealEstateListings;
    import java.util.*;
    import java.io.*;
    public class HouseList {
    
        public ArrayList<House>houseList;
        
        
        public HouseList(String fileName) {
            houseList = new ArrayList<House>();
            try {
                //create scanner to read input
                Scanner sc = new Scanner(new File(fileName));
            
                while(sc.hasNextLine()) {
                    //input reads to parameters    address     price         area          numBedrooms
                    House newListing = new House(sc.next(), sc.nextInt(), sc.nextInt(), sc.nextInt());
                    //add newListing to houseList array
                    houseList.add(newListing);
                }
            }
            catch(FileNotFoundException e)
            {
                System.out.println("File was not found.");
            }
            System.out.println(houseList.size() " houses created.");
            }
            
        public void printHouses(Criteria c) {
            
            for(int i = 0; i<houseList.size();i  ) 
                if(houseList.get(i).satisfies(c))
                    System.out.println(houseList.get(i).toString());
                
            }
        
        public String getHouse(Criteria C) {
            return "";
        }
    }

  

Класс House

 
    package RealEstateListings;
    
    public class House {
        String address;
        int price,area,numberOfBedrooms;
        
        public House(String addr, int salePrice, int saleArea, int numBedrooms) {
            this.address = addr;
            this.price = salePrice;
            this.area = saleArea;
            this.numberOfBedrooms = numBedrooms;
        }
        
        public String getAddress() {return this.address;}
        public int getPrice() {return this.price;}
        public int getArea() {return this.area;}
        public int getNumberOfBedrooms() {return this.numberOfBedrooms;}
        
        public boolean satisfies(Criteria c) {
            
            if(c.getMinimumPrice() <= this.getPrice() amp;amp; c.getMaximumPrice() >= this.getPrice())
                if(c.getMaximumArea() <= this.getArea() amp;amp; c.getMaximumArea() >= this.getArea()) 
                    if(c.getMinNumBedrooms() <= this.getNumberOfBedrooms() amp;amp; c.getMaxNumBedrooms() >= this.getNumberOfBedrooms())
                        return true;
            
            return false;
            
        }
        
        public String toString() {return this.getAddress();}
    }

  

Criteria Class

 
    package RealEstateListings;
    
    public class Criteria {
        
        int minimumPrice, maximumPrice, minimumArea, maximumArea; 
        int minimumNumberOfBedrooms, maximumNumberOfBedrooms;
        
        public Criteria(int minPrice, int maxPrice, int minArea, int maxArea, int minBedrooms, int maxBedrooms) {
            
            this.minimumPrice = minPrice;
            this.maximumPrice = maxPrice;
            this.minimumArea = minArea;
            this.maximumArea = maxArea;
            this.minimumNumberOfBedrooms = minBedrooms;
            this.maximumNumberOfBedrooms = maxBedrooms;
            
        }
        
        public int getMinimumPrice() {return minimumPrice;}
        public int getMaximumPrice() {return maximumPrice;}
        public int getMinimumArea() {return minimumArea;}
        public int getMaximumArea() {return maximumArea;}
        public int getMinNumBedrooms() {return minimumNumberOfBedrooms;}
        public int getMaxNumBedrooms() {return maximumNumberOfBedrooms;}
    }

  

Мой текущий вывод на консоль после запуска:

 Welcome to Mike's House Listing
Please enter the file name of the house list: 
houses.txt
25 houses created.

Please enter your search criteria
Minimum price: 1
Maximum price: 1000000
Minimum area: 1
Maximum area: 1000000
Minimum number of bedrooms: 1
Maximum number of bedrooms: 1000
  

The houses.txt файл содержит строку и три целых числа в каждой строке, я проверил, что ArrayList создается правильно, поэтому моя проблема не связана с этим.

Вопрос / Где я в замешательстве: я пытаюсь использовать функцию printHouses, расположенную в классе HouseList. Я хочу распечатать все дома, которые удовлетворяют критериям, из которых пользователь ввел в метод main, расположенный в классе HouseListTester. Однако, когда пользователь вводит критерии, дома не отображаются. Я не уверен, что является причиной этого, я подозреваю, что это как-то связано с тем, что я неправильно вызываю функцию toString в классе House. Или, возможно, я неправильно вызываю функцию printHouses из метода main. Я вызвал функцию printHouses, используя объект (имя файла), который сначала использовался для создания ArrayList домов, а позже повторно использовал тот же объект для вызова функции printHouses .

Меня беспокоит то, что дома вообще не печатаются, я считаю, что мой удовлетворенный (расположенный в классе критериев) работает правильно, и я также знаю, что объект userCriteria (расположенный в HouseListTester) создан правильно, поскольку я тестирую другие функции из этого класса на вновь созданном объекте.

Почему не печатаются дома, которые удовлетворяют моим указанным критериям?

Спасибо

Ответ №1:

Ваша проблема заключается в вашем satisfies методе в вашем House классе, а не в этом

 public boolean satisfies(Criteria c) {
            
            if(c.getMinimumPrice() <= this.getPrice() amp;amp; c.getMaximumPrice() >= this.getPrice())
                if(c.getMaximumArea() <= this.getArea() amp;amp; c.getMaximumArea() >= this.getArea()) 
                    if(c.getMinNumBedrooms() <= this.getNumberOfBedrooms() amp;amp; c.getMaxNumBedrooms() >= this.getNumberOfBedrooms())
                        return true;
            
            return false;
            
        }
  

Вам понадобится это

 public boolean satisfies(Criteria c) {
            
            if(c.getMinimumPrice() <= this.getPrice() amp;amp; c.getMaximumPrice() >= this.getPrice())
                if(c.getMinimumArea() <= this.getArea() amp;amp; c.getMaximumArea() >= this.getArea()) 
                    if(c.getMinNumBedrooms() <= this.getNumberOfBedrooms() amp;amp; c.getMaxNumBedrooms() >= this.getNumberOfBedrooms())
                        return true;
            
            return false;
            
        }
  

Обратите внимание на эту строку

если(c.getMaximumArea() <= this.getArea() amp;amp; c.getMaximumArea() >= this.getArea())

Должно быть

if(c.getMinimumArea() <= this.getArea() amp;amp; c.getMaximumArea() >= this.getArea())