Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Reading file and adding it to an array through a method

  1. #1
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Reading file and adding it to an array through a method

    I am creating an Array List of zip codes (29000 of them) and I am having trouble getting it to add the complete zipcodes to the arrayList. I think my problem is actually using the ArrayList because it is instantiated in another method.


     
    public class ZipCodeDatabase {
     
     private ArrayList <ZipCode> list;
     
        public ZipCodeDatabase() {
            list = new ArrayList<ZipCode>();
        }
     
        public void readZipCodeData (String filename) throws IOException {
            String info;
            Scanner fileReader;
            Scanner lineReader;
     
            fileReader = new Scanner(new File(filename));
     
            while(fileReader.hasNext()) {
                info = fileReader.nextLine();
     
                lineReader = new Scanner(info);
                lineReader.useDelimiter(",");
     
                int zip = lineReader.nextInt();
                String city = lineReader.next();
                String state = lineReader.next();
                double longtitude = lineReader.nextDouble();
                double latitude = lineReader.nextDouble();
     
                ZipCode z = new ZipCode(zip, city, state, latitude, longtitude);
                list.add(z);
            }
    }

    This uses the ZipCode method which is in another class and has the code

      public ZipCode (int pZip , String pCity , String pState , double pLat , double pLon) {
            zipcode = pZip;
            city = pCity; 
            state = pState;
            latitude = pLat;
            longitude = pLon;
     
     
        }

    The class and method names are all given in the project. I'm a beginner Java student and this is my first time posting on these forums so don't hurt me too badly =P

    Thanks,
    PeskyToaster


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    So what is your problem? Do you get error messages? If so you will need to post them since we don't read minds.
    Improving the world one idiot at a time!

  3. #3
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Reading file and adding it to an array through a method

    Try using the hasNextLine() method of the Scanner class instead of hasNext, see if that makes any difference.
    Unless you explicitly say what's supposed to happen, and what IS happening, we would mainly just need to guess.

    It would be better if you gave more information, i.e. is it only 5 tokens per line in your text file? etc
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  4. #4
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    I'm am testing out a method called

     
     public ZipCode findZip (int zip) {
            ZipCode p = new ZipCode(0);
            for(int i = 0; i < list.size(); i++) {
                if (list.get(i).getZip() == zip) {
                    return list.get(i);
                }
                else {
                    return null;
                }
            }
            return p;
        }

    It should return the entire Zipcode of the text file, for example the first entry of the file is

    99501,ANCHORAGE,AK,61.223145,-149.852843

    So if I input 99501 it should return a toString method of the information which is

    public String toString() {
            address = city + ", " + state + " " + zipcode;
            return address;
        }

    I forgot that the toString is supposed to be in the findZip method as well to format what it returns.

    If I input 99501 I should get ANCHORAGE, AK 99501.
    What I am getting is null.

    I'm also getting a compiler warning of "C:\Users\***\ZipCodeDataBase.java uses unchecked or unsafe operations.
    Recompoile with /XIint:unchecked for details."

    I hope that is enough information

  5. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    Take a look at your if statement. You compare the first ZipCode object to the zipcode you are searching for and if it matches you return the ZipCode object else you return null. Which means your find method will only work if the zipcode you are looking for is the first in the list.
    Improving the world one idiot at a time!

  6. #6
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    Why is it only comparing to the first one?

  7. #7
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    Because that is all you code does.

    Grab the first object in the list
    Do a comparison
    If it matches return object
    Else return null

    It never goes around the loop a second time to compare the second, third etc object in the list. To see what I mean add this line before the if statement:
    System.out.println("Loop #" + i);
    You will see that it will only ever print out one line regardless of which zipcode you search for.
    Improving the world one idiot at a time!

  8. The Following User Says Thank You to Junky For This Useful Post:

    PeskyToaster (November 9th, 2011)

  9. #8
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    What do I need to do to fix this? I thought the i++ would send it through the for loop until it reaches list.size().



    EDIT: By removing the null I can get it to search through the list and find what I need but according to the project I need a null if the zip code input is not found. I also changed the for loop to a while so it looks like this now


     public ZipCode findZip (int zip) {
            ZipCode p = new ZipCode(0);
           int i = 0;
           while (i < list.size()) {
     
                if (list.get(i).getZip() == zip) {
                    return list.get(i);
                }
               /* else {
                    return null;
                }*/
                i++;
            }
            return p;
        }
    Last edited by PeskyToaster; November 9th, 2011 at 08:24 PM.

  10. #9
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    So it isn't returning null. What is it returning instead?
    Improving the world one idiot at a time!

  11. #10
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    When I commented out the null it worked correctly and found the right zip code. But I need to return null if the (int zip) that is inputted is not on the list of zip codes or isn't a valid response.



    EDIT: Figured out the null, I just took it out of the for loop. But I have another problem. For this method I need to search for parts of the city and state that match the give string str. So an str of "al" would return zip codes in all states that start with "al" and all cities that start with "al"
    When I input my string to test it out I get two bracket [ ] so I am assuming it is not correctly adding the matching zip codes to the ArrayList

     public ArrayList search(String str) {
            ArrayList place = new ArrayList(0);
            ArrayList<ZipCode> searchList = new ArrayList<ZipCode>();
            int i = 0;
            while (i < list.size()) {
                str.toUpperCase();
                if ((list.get(i).getCity().substring(0 , str.length()) == str) || (list.get(i).getState().substring(0 , str.length()) == str)) {
                    searchList.add(list.get(i));
     
                }
                /*else {
                return null;
                }*/
                i++;  
                return searchList;
            }
            return place;
        }
    Last edited by PeskyToaster; November 9th, 2011 at 10:19 PM. Reason: Solved previous problem, added highlight

  12. #11
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    Once again what does it return when it doesn't find the zipcode?
    Improving the world one idiot at a time!

  13. #12
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    It only returns two empty brackets []. I am just assuming that it is correctly finding the values and something is wrong with adding it into the searchList

  14. #13
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    Quote Originally Posted by PeskyToaster View Post
    It only returns two empty brackets [].
    That makes no sense. In no way can your program return brackets. Look at your code very carefully. Inside the loop you search for the zipcode and if you find it that zipcode is returned. If it doesn't find it and the loop ends what happens?
    Improving the world one idiot at a time!

  15. #14
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    This code is supposed to search through the list of zip codes by city or state and add the ones that match to an arraylist then return that arraylist. So if I type in "new" it should return NEWARK zip codes and NEW YORK etc. Here's is my main method for testing this

    public class Driver
    {
       public static void main(String[] args) throws IOException{
           ZipCodeDatabase t = new ZipCodeDatabase();
     
           t.readZipCodeData("zipcodes.txt");
     
           System.out.println (t.search("al"));
           System.out.println (t.search("chicago"));

    The output for "al" gives

    []

    The output for "chicago" gives the error

    java.lang.StringIndexOutOfBoundsException: String index out of range: 7
    at java.lang.String.substring(String.java:1955)
    at ZipCodeDatabase.search(ZipCodeDatabase.java:67)
    at Driver.main(Driver.java:22)


    All copied directly from the BlueJ Terminal Window

  16. #15
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    It is not returning the brackets. What your code does now is return an empty ArrayList and if you try to print an empty List that is the output you see. Why does your method now return an ArrayList when the objective is to find a ZipCode object?
    Improving the world one idiot at a time!

  17. #16
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    This is a different method from the first question. I posted the new method I needed help on, on the first page. It seems it is not adding the found Zip Codes to the array list

  18. #17
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    Google "compare strings java"
    Improving the world one idiot at a time!

  19. #18
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    I now have
     
     public ArrayList search(String str) {
     
            ArrayList<ZipCode> searchList = new ArrayList<ZipCode>();
            int i = 0;
            while (i < list.size()) {
                str.toUpperCase();
                if ((list.get(i).getCity().substring(0 , str.length()).equals(str)) || (list.get(i).getState().substring(0 , str.length()).equals(str))) {
                    searchList.add(list.get(i));
     
                } 
                return searchList;
            }
            return null;
        }

    And it still gives the same output

  20. #19
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Reading file and adding it to an array through a method

    You know have a similar issue as you had before. Pretend you are the computer executing the code line by line. Tell me what happens after the code looks at the first element in the list. Of once again add the line of code about printing the number of times around the loop I suggested earlier.
    Improving the world one idiot at a time!

  21. #20
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    I see that it skips right to null but I need to have it there somewhere. I know that I was missing an i++ to keep it going along the while loop. What should I return at the end and where in the loop?


     
    public ArrayList search(String str) {
     
            ArrayList<ZipCode> searchList = new ArrayList<ZipCode>();
            int i = 0;
            while (i < list.size()) {
                str.toUpperCase();
                if ((list.get(i).getCity().substring(0 , str.length()).equals(str)) || (list.get(i).getState().substring(0 , str.length()).equals(str))) {
                    searchList.add(list.get(i));
     
     
                } 
                //return searchList;
     
                i++;
                return searchList;
            }
     
        }


    I'm getting a compile error because it is missing a return statement at the end.

  22. #21
    Junior Member
    Join Date
    Nov 2011
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Reading file and adding it to an array through a method

    I got the above to work but it prints it out all on one line which I can fix. I have a distance method to find the distance between to inputted zip codes

     
     public int distance (int zip1 , int zip2) {
            final double EARTH_RADIUS = 3959;
            int distance;
            double p1 , p2 , p3;
     
            ZipCode z1 = findZip(zip1);
            ZipCode z2 = findZip(zip2);
     
            double lat1 = Math.toRadians((z1.getLatitude()));
            double lat2 = Math.toRadians((z2.getLatitude()));
            double long1 = Math.toRadians((z1.getLongitude()));
            double long2 = Math.toRadians((z2.getLongitude()));
     
            p1 = (Math.cos(lat1)) * (Math.cos(long1)) * (Math.cos(lat2)) * (Math.cos(long2));
            p2 = (Math.cos(lat1)) * (Math.sin(long1)) * (Math.cos(lat2)) * (Math.sin(long2));
            p3 = (Math.sin(lat1)) * (Math.sin(lat2));
     
            distance = (int)((Math.acos(p1 + p2 + p3)) * (EARTH_RADIUS));
     
            return distance;
     
        }

    The math is off though because if I input 49401 and 90001 the output should be 1841 miles but my output is 2229. I also need to have an if that doesn't accept null values for the entered zips (if zip1 is not on the list) and I have no idea how to do that.

Similar Threads

  1. Reading file of floats into array list and sorting into subsets
    By Skave in forum Collections and Generics
    Replies: 2
    Last Post: November 9th, 2011, 07:03 PM
  2. Reading from a sequential file to an array
    By Xrrak in forum File I/O & Other I/O Streams
    Replies: 15
    Last Post: August 20th, 2011, 01:33 PM
  3. Reading lines of a text file into a string array
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 11th, 2010, 11:56 AM
  4. Reading a file, then putting it in an array
    By Gondee in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 16th, 2010, 11:11 AM
  5. Method Adding elements to an array with certain restrictions
    By Newoor in forum Collections and Generics
    Replies: 1
    Last Post: December 13th, 2009, 11:13 AM