从类创建对象数组

时间:2014-04-01 23:03:49

标签: java arrays class object

public class PostalCodes {
private String city;
private double latitude;
private double longitude;
private String zip;
private String state;

public PostalCodes(String aZip, String aCity, String aState, double aLatitude, double aLongitude)
{
    city = aCity;
    latitude = aLatitude;
    longitude = aLongitude;
    zip = aZip;
    state = aState;
}

void setZip(String aZip)
{
    zip=aZip;
}

void setState(String aState)
{
    state=aState;
}


void setLocation(String aCity)
{
    city = aCity.trim();
}
void setLatitude(double lat)
{
    latitude = lat;
}
void setLongitude(double long1)
{
    longitude = long1;
}
public String getState()
{
    return state;
}
public String getZip()
{
    return zip;
}
public String getLocation()
{
    return city;
}
public double getLatitude()
{
    return latitude;
}
public double getLongitude()
{
return longitude;
}
public String toString()
{
    String result = String.format("%s %s,%s (%1.3f; %1.3f)",zip, city, state, latitude,longitude);
    return result;
}

} 以上是我的班级我试图制作一个50000及以下的阵列是我的主...

public class Hmwk {

public static void main(String[] args) throws IOException {
    URL url = new URL("http://noynaert.net/zipcodes.txt");
    Scanner input=new Scanner (url.openStream());
    int counter =0;
    final int MAX_SIZE=50000;
    PostalCodes[] codesArray= new PostalCodes[50000];
    while (input.hasNextLine() && counter < MAX_SIZE)
    {
        String line=input.nextLine();
        String[] tokens;
        tokens = line.split("\t");
        if (tokens.length != 5)
        {
            continue;
        }
        String zip=tokens[0];
        String city=tokens[1];
        String state=tokens[2];
        double lat=Double.parseDouble(tokens[3]);
        double longy=Double.parseDouble(tokens[4]);
        PostalCodes code=new PostalCodes(zip,city,state,lat,longy);
        codesArray[counter]= code; //Error here
        //System.out.println(code.toString());
        counter++;
    }

                for (int i =0;i<counter; i+=1000)
    {
                  System.out.println(codesArray[i].toString());
    }
}

我试图在我的阵列中将前50000条目保存为095601 Amador City,CA (38.427; -120.828),095604 Auburn,CA (39.106; -120.536), 095605 West Sacramento,CA (38.592; -121.528)等。我能够打印出我想要的格式,但我无法弄清楚如何将它添加到数组中。谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

您的代码正在尝试将String添加到PostalCodes数组中,但实际上您想要添加PostalCodes对象。

移除对toString()的调用:

PostalCodes code = new PostalCodes(zip,city,state,lat,longy);
codesArray[counter] = code;

顺便说一句,我建议将您的班级重命名为单数PostalCode

答案 1 :(得分:0)

我建议你使用Java提供的Collection framework。

List<PostalCodes> postalCodeList = new ArrayList<PostalCodes>(50000);

PostalCodes code = new PostalCodes(zip,city,state,lat,longy);
postalCodeList.add(code);