Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use == in your of condition.

Also, no need for the doubke-quotes around null.

Finally, 'return null' needs to be outside of your for loop. Otherwise, on the first non-match, it will return null. You want to wait for the whole loop (all zips) to be compared before returning null. On a match, you can return right away.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...