Search code examples
javaloopsbooleanincompatibletypeerror

My loop boolean is not compiling


I need this method to go through my ArrayList myZip, find whether or not there is an integer in there that matches int zip, then go and find the ZipCode that is equal to intZip; if there is no match then return null.

public ZipCode findZip(int zip) {
    for (int i = 0; i < myZips.size(); i++) {
        if (zip == myZips.get(i)) 
            return myZips.get(i);}
        return null;
}

Any ideas?

Here's the ZipCode Class:

public class ZipCode {

    private int zipCode;
    private String city;
    private String state;
    private double longitude;
    private double latitude;


    public ZipCode(int pZip) {
        zipCode   = pZip;
        city      = "UNKOWN";
        state     = "ST";
        latitude  = 0.0;
        longitude = 0.0;
    }

    public ZipCode (int pZip, String pCity, String pState, double pLat, double pLon) {
        zipCode   = pZip;
        city      = pCity;
        state     = pState;
        latitude  = pLat;
        longitude = pLon;

    }

    public void setZipCode(int zipCode){
        this.zipCode = zipCode;
    }

    public void setCity (String city){
        this.city = city;
    }

    public void setState (String state){
        this.state = state;
    }

    public void setLatitude (double latitude){
        this.latitude = latitude;
    }

    public void setLongitude (double longitude){
        this.longitude = longitude;
    }

    public int getZipCode (){
        return zipCode;
    }

    public String getCity (){
        return city;
    }

    public String getState(){
        return state;
    }

    public double getLatitude(){
        return latitude;
    }

    public double getLongitude(){
        return longitude;
    }

    public String toString(){
        return city + ", " + state + zipCode;
}
}

I really just need to know how to make the findZip method return the ZipCode that is the same as int zip.

This is eventually going to pull from a file.txt that has addresses formatted like this: 94594, MerryVille, WA, Longitude, Latitude


Solution

  • I'm guessing you want something like this.

    List<ZipCode> myZips = // create all ZipCode's somehow
    
    public ZipCode findZip(int zip){
    
        //look at all zips
        for(ZipCode zipCode : myZips){
    
            //if we find one that matches the one we want, return it
            if(zipCode.getZipCode() == zip){
                return zipCode;
            }
        }
    
        // we checked all our zip's and couldn't find this one
        return null;
    }