【发布时间】:2016-02-10 11:04:19
【问题描述】:
由于某种原因,当我传递我的 ArrayList(它是来自 Java 的 Lang.* 的基本 ArrayList)一个 int 变量时,而不是在变量 int 的索引处获取项目(例如: i = 0; arrayList.get(i); 应该是第一个ArrayList 中的项目) - 它调用 WHOLE 列表。
下面是有问题的方法:
public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(00000);
//System.out.println(zips.get(0)); here gives 99501,ANCHORAGE,AK
//System.out.println(zips.get(0).getZipCode()); here gives 99501
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
//System.out.print(aZip); here gives the zip codes from the whole array
else
aZip = null;
}
return aZip;
//Therefore, aZip is ALWAYS null. Even if it exists.
}
我尝试了一系列故障排除来解决这个问题。到目前为止,我了解到当我输入一个直整数时不会出现问题(例如: arrayList.get(1); 正常获取第二项)。不幸的是,没有要显示的编译器错误。
null 。
我需要使用一个 int 所以我可以增加它来遍历列表,这也很不幸。
更大的程序片段:(与我之前的问题相同)
import java.util.*;
import java.io.*;
import java.lang.Math;
public class ZipCodeDatabase {
//Field
private ArrayList<ZipCode> zips;
//Constructor
public ZipCodeDatabase () {
zips = new ArrayList<ZipCode> ();
}
//Mutator Method
public void readZipCodeData(String filename) {
Scanner inFS = null;
FileInputStream fileByteStream = null;
try{
// open the File and set delimiters
fileByteStream = new FileInputStream(filename);
inFS = new Scanner(fileByteStream);
inFS.useDelimiter("[,\r\n]+");
// continue while there is more data to read
while(inFS.hasNext()) {
//read in all input
int aZip = inFS.nextInt();
String aCity = inFS.next();
String aState = inFS.next();
double aLat = inFS.nextDouble();
double aLon = inFS.nextDouble();
//Create and add new zipcode
ZipCode newZip = new ZipCode(aZip, aCity, aState, aLat, aLon);
zips.add(newZip);
}
fileByteStream.close();
// Could not find file
}catch(FileNotFoundException error1) {
System.out.println("Failed to read the data file: " + filename);
// error while reading the file
}catch(IOException error2) {
System.out.println("Oops! Error related to: " + filename);
}
}
//Accessor Methods
public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(00000);
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
else
aZip = null;
}
return aZip;
}
这是 getZipCode() 方法(它返回邮政编码 int,是包含纬度和经度的一小部分 int 的一部分;我有一个数组):
public int getZipCode () {
return zipCode;
}
【问题讨论】:
-
什么是
zips?您能否展示一个重现问题的完整示例? -
你为什么有
else aZip = null?这将更改aZip以引用null,即使在循环的早期找到匹配项也是如此。我认为您根本不想要else声明。 -
向我们展示来自
zips和 ZipCode 类的代码。 -
getZipCode()的返回类型是什么? -
你在哪里发布了
getZipCode()方法?
标签: java variables arraylist methods