For some reason, when I pass my ArrayList (which is a basic ArrayList from Java's Lang.*) an int variable, instead of taking the item at the index of the variable's int (eg: i = 0; arrayList.get(i); should be the first item in the ArrayList) - it calls the WHOLE list.
Here's the method in question:
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.
}
I've tried a bunch of troubleshooting to figure it out. So far, I've learned that the issue doesn't arise when I put a straight integer in (eg: arrayList.get(1); gets the second item as normal). There's no compiler error to show, unfortunately.
null when it runs.
I need to use an int so I can increment it to run through the list, also unfortunate.
Larger Clip of Program: (Same as from my prior question)
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;
}
Here's the getZipCode() method (it returns the zip code int, a part of a small collection of ints including latitude and longitude; of which I have an array):
public int getZipCode () {
return zipCode;
}
zips? Can you show a complete example that reproduces the problem?else aZip = null? That will changeaZipto refer tonulleven if a match was found earlier in the loop. I don't think you want thatelsestatement at all.zipsand ZipCode class.getZipCode()?getZipCode()method?