gpt4 book ai didi

java - 从类创建对象数组

转载 作者:行者123 更新时间:2023-12-01 13:11:49 25 4
gpt4 key购买 nike

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) ) 等在我的数组中。我能够打印出我想要的格式,但我不知道如何将其添加到数组中。感谢您抽出时间。

最佳答案

您的代码试图将一个字符串添加到 PostalCodes 数组中,但您实际上想要添加一个 PostalCodes 对象。

删除对 toString() 的调用:

PostalCodes code = new PostalCodes(zip,city,state,lat,longy);
codesArray[counter] = code;
<小时/>

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

关于java - 从类创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com