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 15 of 15

Thread: I/O Help with Collections/Ordering?

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default I/O Help with Collections/Ordering?

    I am trying to finalize a project in Java, however I am having a hard time getting the Collections.sort to work and sort my output by natural order. Basically I should be getting:

    Total properties listed: 7
    Total value of properties listed: 2120000.00

    110001
    110020
    110223
    110333
    110421
    110442
    112352

    But I am getting:

    Total properties listed: 7
    Total value of properties listed: $2120000.00

    110001
    110223
    110020
    110333
    110442
    110421
    112352

    Everything is working except for my natural ordering of the ID numbers listed at the bottom. If anyone can take a look through my code and let me know what I might be doing wrong here any help would be appreciated! Thanks!

     package kettask2pt2;
     
    import java.util.Scanner;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileReader;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.*;
    /**
     *
     * @author Brandon
     */
     
    public class KETTask2Pt2{
       public static void main(String[] args) throws FileNotFoundException, IOException
        {
     
          // Ask for the file name listings.txt
     
            Scanner inputscan = new Scanner(System.in);
            System.out.print("Please enter listings.txt: ");
            String inputFile = inputscan.next();
     
          // Creates variables & BufferedWriters
            String line = null ;
            PrintWriter out = new PrintWriter("overview.txt");
            File input = new File(inputFile);
            BufferedReader in = new BufferedReader(new FileReader(input));
            int count = 0;
            double sum = 0;
     
          // Totals and adds properties listed and the values of the properties  
      while ((line = in.readLine())!= null)     
                {
                count++;
                String[] thelist = line.split("[\\s}]");
                Double totalvalue = Double.parseDouble(thelist[2]);
     
    	       {
                    sum+=totalvalue;
                   }        
                }
                out.println("Total properties listed:  " + count);
                out.println("Total value of properties listed: " + "$" +sum + "0" +"\n");
                in.close();
     
         //Adds the id numbers for the individual listings              
          try {
                 ArrayList<String> ids = new ArrayList<String>();
                 Scanner idscan = new Scanner((input)); 
     
               while (idscan.hasNextLine())
               {              
                 line = idscan.nextLine();
                 String[] fields = line.split("[\\s}]");
                 String idnums = (fields [0]);      
     
                       {
                        Collections.sort(ids);            
                     out.println(idnums);                      
                        in.close();
     
                       }
                    }
                }catch(Exception e){              
                       }           
                 //closes the print writer
                    out.flush();
                out.close();
            }
    }
    Last edited by BTaggar; August 26th, 2013 at 09:59 PM. Reason: code tags

  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: I/O Help with Collections/Ordering?

    What does the file look like?

  3. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

    The file is a .txt file with the following contents

    110001 commercial 500000.00 101
    110223 residential 100000.00 101
    110020 commercial 1000000.00 107
    110333 land 30000.00 105
    110442 farm 200000.00 106
    110421 land 40000.00 107
    112352 residential 250000.00 110

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

    Default Re: I/O Help with Collections/Ordering?

    Why have you declared a Scanner and 2 BufferedReaders? Especially when you don't even use the second BufferedReader. Why do you read the file twice? That's a waste of time and resources. Read the file once and process each line fully. You sort the ArrayList ids but you never insert any data into it.
    Improving the world one idiot at a time!

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

    BTaggar (August 27th, 2013)

  6. #5
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

    The only reason I have 2 buffered readers and am wasting time and resources is because I came with this code after a lot of trial and error haha, it may seem simple, but to me this is like a foreign language I am learning... The data is inserting into the text file, and it looks like I am sorting it before I insert it, but you are saying that I am not correctly placing it into the array list before displaying it, correct?

    --- Update ---

    Also, I removed the unused BufferedReader, thanks for the heads up!

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

    Default Re: I/O Help with Collections/Ordering?

    That is exactly what I am saying. Read your code carefully. Look at the input and output files. They are exactly the same. Doesn't that ring bells? What your code does is read a line of text, extracts the ID number and writes it out to the output file. Nowhere in your code do you insert data into the ArrayList or extract the data back out of the ArrayList.
    Improving the world one idiot at a time!

  8. #7
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

    Good call, I am assuming I can add the information to the array list by using

    ids.add(idnums);

    and call it by using the

    ids.get(idnums)

    is this close?

  9. #8
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: I/O Help with Collections/Ordering?

    What happened when you tried?

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

    Default Re: I/O Help with Collections/Ordering?

    Try it an see.

    However, the get method presumably would retrieve something from the list. So what is the point if you already have it stored in the idnums variable?
    Improving the world one idiot at a time!

  11. #10
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

    The code below I tried, and this is what I got:

    Total properties listed: 7
    Total value of properties listed: $2120000.00

    110001
    110001
    110223
    110001
    110020
    110223
    110001
    110020
    110223
    110333
    110001
    110020
    110223
    110333
    110442
    110001
    110020
    110223
    110333
    110421
    110442
    110001
    110020
    110223
    110333
    110421
    110442
    112352


         //Adds the id numbers for the individual listings              
          try {
                 ArrayList<String> ids = new ArrayList<String>();                     
                 Scanner idscan = new Scanner((input)); 
     
               while (idscan.hasNextLine())
     
     
     
               {              
                 line = idscan.nextLine();
                 String[] fields = line.split("[\\s}]");
                 String idnums = (fields [0]);  
                 ids.add(idnums);
                  Collections.sort(ids);
                       {
     
                        int arraysize = ids.size();
                             for(int i=0; i<arraysize; i++){
                           out.println(ids.get(i));           
                             }             
                        in.close();
     
                       }
                    }
                }catch(Exception e){              
                       }           
                 //closes the print writer
                    out.flush();
                out.close();
            }
    }

  12. #11
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: I/O Help with Collections/Ordering?

    Compare the input file to the output and find the pattern to see what the code is doing

  13. #12
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

    I appreciate you guys helping me understand this, and I apologize for my slow learning here, I will get this eventually!

    So in that code I have what I need, however I have way more than I want as well.... I guess I figured I needed to pull from the list to get it sorted the way I need it, as when I just print idnums I get the same issue. They will print but not sorted

    --- Update ---

    Got it, I see that it is printing essentially (1), (1,2), (1,2,3) etc.. but I am not sure how to just tell it to print the last read through

  14. #13
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: I/O Help with Collections/Ordering?

    Quote Originally Posted by BTaggar View Post
    Got it, I see that it is printing essentially (1), (1,2), (1,2,3) etc.. but I am not sure how to just tell it to print the last read through
    110001
    110001, 110223
    110001, 110020, 110223
    110001 ,110020, 110223, 110333
    110001, 110020, 110223, 110333, 110442
    110001, 110020, 110223, 110333, 110421, 110442
    110001, 110020, 110223, 110333, 110421, 110442, 112352
    Pay very close attention to what it is doing. Follow the code line by line.
    Get a value. Add the value to the list. Sort the list. Output the list.
    Get next value. Add value. Sort list. Output list.
    Get next value. Add value. Sort list. Output list.
    ~etc

    Some of those things do not need to be done every iteration of the loop, but only once after all of the data is in the list

    Post the new version of the code so we can see the overall picture again, Junky brought up some points that should be tended to

  15. The Following User Says Thank You to jps For This Useful Post:

    BTaggar (August 27th, 2013)

  16. #14
    Junior Member
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: I/O Help with Collections/Ordering?

     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package kettask2pt2;
     
    import java.util.Scanner;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileReader;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.*;
    /**
     *
     * @author Brandon
     */
     
    public class KETTask2Pt2{
       public static void main(String[] args) throws FileNotFoundException, IOException
        {
     
          // Ask for the file name listings.txt
     
            Scanner inputscan = new Scanner(System.in);
            System.out.print("Please enter listings.txt: ");
            String inputFile = inputscan.next();
     
          // Creates variables & BufferedWriters
            String line = null ;
            PrintWriter out = new PrintWriter("overview.txt");
            File input = new File(inputFile);
            BufferedReader in = new BufferedReader(new FileReader(input));   
            int count = 0;
            double sum = 0;
     
          // Totals and adds properties listed and the values of the properties  
      while ((line = in.readLine())!= null)     
                {
                count++;
                String[] thelist = line.split("[\\s}]");
                Double totalvalue = Double.parseDouble(thelist[2]);
     
    	       {
                    sum+=totalvalue;
                   }        
                }
                out.println("Total properties listed:  " + count);
                out.println("Total value of properties listed: " + "$" +sum + "0" +"\n");
                in.close();
     
         //Adds the id numbers for the individual listings              
          try {
                 ArrayList<String> ids = new ArrayList<String>();                     
                 Scanner idscan = new Scanner((input)); 
     
              while (idscan.hasNextLine())
     
     
     
               {              
                 line = idscan.nextLine();
                 String[] fields = line.split("[\\s}]");
                 String idnums = (fields [0]);  
                 ids.add(idnums);
                  Collections.sort(ids);
                       {
     
                        int arraysize = ids.size();
                             for(int i=0; i<arraysize; i++){
                           out.println(ids.get(i));           
                             }             
                        in.close();
     
                       }
                    }
                }catch(Exception e){              
                       }           
                 //closes the print writer
                    out.flush();
                out.close();
            }
    }
    }


    --- Update ---

    Here is where I am at right now and the results I am getting

    Total properties listed: 7
    Total value of properties listed: $2120000.00

    110001
    110001
    110223
    110001
    110020
    110223
    110001
    110020
    110223
    110333
    110001
    110020
    110223
    110333
    110442
    110001
    110020
    110223
    110333
    110421
    110442
    110001
    110020
    110223
    110333
    110421
    110442
    112352

    --- Update ---

    I feel like I am getting closer, but still struggling with why it is reading it so many times and creating those duplicates

    --- Update ---

    Sorry I posted the wrong code before..

    --- Update ---

    It took me a while, but I finally got there! Thank you all for your help! Here is my final code:

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package kettask2pt2;
     
    import java.util.Scanner;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileReader;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.*;
    /**
     *
     * @author Brandon
     */
     
    public class KETTask2Pt2{
       public static void main(String[] args) throws FileNotFoundException, IOException
        {
     
          // Ask for the file name listings.txt
     
            Scanner inputscan = new Scanner(System.in);
            System.out.print("Please enter listings.txt: ");
            String inputFile = inputscan.next();
     
          // Creates variables & BufferedWriters
            String line = null ;
            PrintWriter out = new PrintWriter("overview.txt");
            File input = new File(inputFile);
            BufferedReader in = new BufferedReader(new FileReader(input));   
            int count = 0;
            double sum = 0;
            ArrayList<String> ids = new ArrayList<String>(); 
          // Totals and adds properties listed and the values of the properties  
      while ((line = in.readLine())!= null)     
                {
                    String[] fields = line.split("[\\s}]");
                    ids.add(fields[0]);
                    String idnums = (fields [0]); 
                count++;
                String[] thelist = line.split("[\\s}]");
                Double totalvalue = Double.parseDouble(thelist[2]);
     
    	       {
                    sum+=totalvalue;
                   }        
                }
                out.println("Total properties listed:  " + count);
                out.println("Total value of properties listed: " + "$" +sum + "0" +"\n");
                in.close();
     
         //Adds the id numbers for the individual listings              
          try {                                                                                
                  Collections.sort(ids);            
                             {
                       {
                        for(Object propertyNumber : ids)
                        out.println(propertyNumber);
     
                             }             
                        in.close(); 
                       }
     
                }catch(Exception e){              
                       }           
                 //closes the print writer
                    out.flush();
                out.close();
            }
    }

  17. #15
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: I/O Help with Collections/Ordering?

    What does idnums do?
    inputscan is never closed.

    --- Update ---

    String[] fields = line.split("[\\s}]");
    String[] thelist = line.split("[\\s}]");
    No need to parse the string twice

  18. The Following User Says Thank You to jps For This Useful Post:

    BTaggar (August 27th, 2013)

Similar Threads

  1. Problem ordering nested collections
    By PauloSotto in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 13th, 2013, 02:11 PM
  2. Loop ordering in matrix multiplication
    By murph in forum Loops & Control Statements
    Replies: 3
    Last Post: November 24th, 2011, 03:08 AM
  3. heap ordering using binary tree
    By student in forum Java Theory & Questions
    Replies: 5
    Last Post: October 27th, 2010, 05:25 PM
  4. Deciding Interceptor Ordering?
    By arpitgadle in forum Web Frameworks
    Replies: 1
    Last Post: August 10th, 2010, 05:33 AM
  5. [SOLVED] Problem with Ordering an Arraylist of Comparable Objects.
    By Faz in forum Collections and Generics
    Replies: 8
    Last Post: June 16th, 2010, 06:36 PM