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

Thread: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

  1. #1
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    /**
    * OverView: TMapKey is not separated from TMapEntry for navigation purposes.
    * This should be Very Easy (3 field Input File), Sort, Load TMap and "Get" TMapkey).
    *
    * Read UnSorted sequential text file in as Input and display Input recs.
    * Text Input File Layout(fixed): bytes 1=>4(key) byte5(delimeter) rest of file=(value)
    *
    * Sort, Put TMap and Display (sorts fine but, does not separate key, delimeter and value)
    * Because no separation of those 3 fields causes my TMap navigation to Fail.
    *
    * Write Output Clean.txt file from Sorted records - this file is Sorted correctly "as is".
    *
    * Console entry: 80.a Record "80.a" exists on Input and in TMap
    * Does not separate TMapKey from TMapEntry. TMap "Get" does not work.
    * This is my BIGGEST Problem.
    *
    * I'd like to see TMapKey as a true key field not as Key+Delimeter+Value.
    * My TMapEntry is input record strung twice across.

    I am using BlueJ if that matters (relatively new version).
    */
    Attached Files Attached Files

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Do you have a java programming question?

    Please copy and post all error messages and the source code here on the forum.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Yes. I have a Java program question. I thought "What's Wrong With My Code" was the best option to choose from. My bad, first timer. I hope I did this correctly this time.

    Problem: My TreeMap "tm.get" does not work.
    Most likely cause is my tm.put command and inability to break up my TM.Entry(s) field into Key and Value. I only have this problem when I use a .txt file as input (hardcoded "put(s)" are not a problem for me).
    I need the "tm.get" to work before I can issue TM navigational instructions.

    Program compiles and runs thru completion (no errors). Reads Quiz1Q.txt (Input file) well, Writes out a good sorted "...clean.txt" file, accepts console entry well but, does not find my TM key (tm.get(id)).

    I am guessing it is a simple matter of my handling either the input file (non-array use) or it's my TMap definition or both not using/using "String". This problem is definitely driving me crazy (did A TON of research - no luck). I cannot Wait to see what it is that I did wrong.
    http://www.javaprogrammingforums.com/yemotions/38.gif

    I originally attached program and input .txt files but, I can copy and paste my TMDemo code here, sure. I have more comments in the TMDemo code below. I have also attached TMDemo code and Quiz1Q.txt (Input file).

    Quiz1Q.txt (Input file, key (bytes 1=>4), followed by delimiter "," followed by value data).

    TMDemo Code:

    import java.text.Collator;
    import java.util.Set;
    import java.io.*; // This has BufferedReader and more in it
    import java.util.TreeMap; // This allows you to use TreeMap elements
    import java.util.*; // This allows you to use Scanner (find out more precise)
    //"C:\\Users\\Don\\Documents\\Quiz1Q.txt"
    /**
    * OverView: TMapKey is not separated from TMapEntry for navigation purposes.
    * This should be Very Easy (3 field Input File), Sort, Load TMap and "Get" TMapkey.
    * Read UnSorted sequential text file in as Input and display Input recs.
    * Text File Layout(fixed): bytes 1=>4(key) byte5(delimeter) rest of file=(value)
    * Sort, Put TMap and Display (sorts fine but, does not separate key, delimeter and value)
    * Because no separation of those 3 fields causes my TMap navigation to Fail.
    * Write Output Clean.txt file from Sorted records - this file is Sorted correctly "as is".
    * Console entry (80.a)
    * Does not separate TMapKey from TMapEntry. TMap "Get" does not work.
    * This is my BIGGEST Problem.
    *
    * I'd like to see TMapKey as a true key field not as Key+Delimeter+Value.
    * My TMapEntry is input record strung twice across.
    */

    public class TMDemo {
    // Removed most of my parameter passing = "C:\\Users\\Don\\Documents\\Quiz1Q.txt" broken down,
    // For easier reviewing of meaningful code. ???
    private static String endOfLine = "\n";
    private static String Subscr = "1";

    /**
    * The main function.
    * @param args - Removed most to make code easier to read
    */
    public static void main(String[] args) throws Exception {
    String line = null;
    System.out.println("Set String Line to null");
    BufferedReader fileReader =
    new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Quiz1Q.txt" ));
    System.out.println(" Just after BufferedReader : " + fileReader);
    //* = new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Quiz1Q.txt" ));
    FileWriter fileWriter = new FileWriter("C:\\Users\\Don\\Documents\\clean.txt") ;
    System.out.println(" Just after FileWriter Defined : " + fileWriter);
    {
    /**
    * The tree_map defined.
    */
    TreeMap<String, String> tm = new TreeMap<String, String>(); // take out >() That made no diff

    System.out.println(" Start sorting/looping Input here using - display Once");
    while((line = fileReader.readLine()) != null) // Loops Read for each Quiz1Q record
    {
    tm.put(line, line); // Loads the tree_map POORLY

    System.out.println("Input " + line); //Prints each Quiz1Q rec Unsorted (key&value as one)

    }
    fileReader.close();
    System.out.println("fileReader.close and Loop Writing each Sorted Quiz1Q rec to Clean.txt");
    for (String keyin : tm.values()) { // For Each Loop=> Writes the Sorted Quiz1Q file
    // to output Clean.txt file
    fileWriter.write(keyin + endOfLine);
    // // Prints each Sorted Quiz1Q. If you add + end0fLine gets a
    // lot of wrap around non printable data 3 lines worth.
    System.out.println("Sorted " +keyin);

    }

    fileWriter.close(); // This is the end of Clean.txt Writes (output file)
    // Displaying the TreeMap
    System.out.println("Initial Mappings are: " + tm);
    System.out.println(" Select a Search key : "); // prints after
    //System.out.println("Value of "+QKey+" is: "+tree_map.get(keyin));
    Scanner console = new Scanner(System.in);
    String QKey = console.next(); // Is my entry for Search Key use: 80a.

    System.out.println("Value of "+QKey+" is: "+tm.get(QKey));
    // Getting the value of selected key in println get
    // I have not yet figured out how to get the key with the first 4 char's ex: "80.a"
    String id = QKey;
    System.out.println("B4 Nested*The Key is: " + id);

    if (tm.containsKey(id)){
    //** Keep if (tm.containsKey("80.a")) {
    System.out.println("*Nested*The keySetis: " + tm.keySet());

    System.out.println("*Nested*The Key is: " + id);
    // Getting the value of selected key
    System.out.println("*Nested*The IDVal is: " + tm.get(id));
    System.out.println("*Nested*The Value is: " + tm.get("80.a"));
    }
    System.out.println("The Value Key is: " + tm.get(id)); //returns null if no Higher
    System.out.println("The First Key is: " + tm.firstKey()); //returns null if no Higher
    System.out.println("The FirstEntry is: " + tm.firstEntry()); //returns null if no Higher
    System.out.println("The Last Key is: " + tm.lastKey()); //returns null if no Higher
    System.out.println("The LastKEntry is: " + tm.lastEntry()); //returns null if no Higher

    String element1 = (String) tm.get(id);
    // String element1 = (String) tm.get("01.a");
    System.out.println("The String Key is: " + element1);

    int entryCount = tm.size();
    System.out.println("Number of Loaded Entries in tm.map is: " + entryCount);
    }
    }
    }
    Attached Files Attached Files

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.

    Can you copy the contents of the console that shows what is wrong and paste it here?
    Also add some comments (for example: <<<<<<<< This should be 44) that point out the problems with the output
    and show what the desired output is.

    A suggestion for testing: Reduce the size of the input file to less than 10 lines. 5?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Can you tell this is my first ever post? Sorry. I'll do better next time.

    First (below) I have pasted program TMDemo Code with code tags, then Console contents at the bottom (last 10 lines). I have used "<<<<<", ">>>>>" and "<><>" as comment identifiers.

    I have also attached the program (TMDemo) along with "code tags", Input file Quiz1Q.txt and entire console content file.
    Input Quiz1Q.txt File Layout(fixed): bytes 1=>4(key) byte5(delimeter) rest of file=(value)
    Ex:
    80.a,Question for 80 a?

    I hope I got things right this time. Thank you for being patient.

    TMDemo:

    import java.text.Collator;
    import java.util.Set;
    import java.io.*;                   // This has BufferedReader and more in it
    import java.util.TreeMap;        // This allows you to use TreeMap elements
    import java.util.*;                 // This allows you to use Scanner (find out more precise)
    //"C:\\Users\\Don\\Documents\\Quiz1Q.txt"
    /**
     * OverView:  TMapKey is not separated from TMapEntry for navigation purposes. 
     * This should be Very Easy (3 field Input File), Sort, Load TMap and "Get" TMapkey.
     *   Read UnSorted sequential text file in as Input and display Input recs.
     *      Text File Layout(fixed):  bytes 1=>4(key) byte5(delimeter) rest of file=(value)
     *   Sort, Put TMap and Display (sorts fine but, does not separate key, delimeter and value) 
     *      Because no separation of those 3 fields causes my TMap navigation to Fail. 
     *   Write Output Clean.txt file from Sorted records - this file is Sorted correctly "as is".
     *   Console entry (80.a) 
     *      Does not separate TMapKey from TMapEntry.  TMap "Get" does not work.
     *      This is my BIGGEST Problem.  
     *      
     *      I'd like to see TMapKey as a true key field not as Key+Delimeter+Value.  
     *      My TMapEntry is input record strung twice across.
     */
     
    public class TMDemo {
     // Removed most of my parameter passing = "C:\\Users\\Don\\Documents\\Quiz1Q.txt" broken down to:
     // For easier reviewing of meaningful code.
     private static String endOfLine         = "\n";
        private static String Subscr            = "1";
     
        /**
         * The main function.
         * @param args - Removed most to make code easier to read 
         */
        public static void main(String[] args) throws Exception {   
            String line                = null;
               System.out.println("Set String Line to null"); 
             BufferedReader fileReader = 
                new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Quiz1Q.txt"));
             System.out.println("     Just after BufferedReader : " +  fileReader);
           //* = new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Quiz1Q.txt"));
             FileWriter fileWriter = new FileWriter("C:\\Users\\Don\\Documents\\clean.txt");
             System.out.println("     Just after FileWriter Defined : " +  fileWriter);
           {
         /**
          * The tree_map defined.
          */
        TreeMap<String, String> tm = new TreeMap<String, String>();  // take out >() That made no diff
     
             System.out.println(" Start sorting/looping Input here using - display Once");
                while((line = fileReader.readLine()) != null)    // Loops Read for each Quiz1Q record
            {   
                  tm.put(line, line);   //   Load the tree_map
     
                System.out.println("Input  " + line);   //Prints each Quiz1Q rec Unsorted (key&value as one)
     
        }
            fileReader.close();
               System.out.println("fileReader.close and Loop Writing each Sorted Quiz1Q rec to Clean.txt");     
         for (String keyin : tm.values()) {   // For Each Loop=> Writes the Sorted Quiz1Q file    
                                          // to output Clean.txt file
                fileWriter.write(keyin + endOfLine);
                              // // Prints each Sorted Quiz1Q.  If you add + end0fLine gets a 
                              // lot of wrap around non printable data 3 lines worth.
                  System.out.println("Sorted  " +keyin);  
     
        }
     
            fileWriter.close();             // This is the end of Clean.txt Writes (output file)
           // Displaying the TreeMap 
           System.out.println("Initial Mappings are: " + tm); 
           System.out.println(" Select a Search key : ");  // prints after 
           //System.out.println("Value of "+QKey+" is: "+tree_map.get(keyin)); 
           Scanner console = new Scanner(System.in);
           String QKey = console.next();            // Is my entry for Search Key  use: 80a.
     
           System.out.println("Value of "+QKey+" is: "+tm.get(QKey)); 
           // Getting the value of selected key in println get
           // I have not yet figured out how to get the key with the first 4 char's ex: "80.a"
            String id = QKey;
            System.out.println("B4  Nested*The Key   is: " + id); 
     
            if (tm.containsKey(id)){
               //** Keep        if (tm.containsKey("80.a")) {
              System.out.println("*Nested*The keySetis: " + tm.keySet());
     
              System.out.println("*Nested*The Key   is: " + id); 
           // Getting the value of selected key 
            System.out.println("*Nested*The IDVal is: " + tm.get(id));
            System.out.println("*Nested*The Value is: " + tm.get("80.a"));  
        }
            System.out.println("The Value  Key is: " + tm.get(id)); //returns null if no Higher
            System.out.println("The First  Key is: " + tm.firstKey()); //returns null if no Higher
            System.out.println("The FirstEntry is: " + tm.firstEntry()); //returns null if no Higher
            System.out.println("The Last   Key is: " + tm.lastKey()); //returns null if no Higher
            System.out.println("The LastKEntry is: " + tm.lastEntry()); //returns null if no Higher
     
            String element1 = (String) tm.get(id);
            //  String element1 = (String) tm.get("01.a");
                    System.out.println("The String Key is: " + element1);
     
        int entryCount = tm.size();  
                      System.out.println("Number of Loaded Entries in tm.map is: " + entryCount);
        }
    }
    }


    Console Contents:

    80.a <><><><><><> This is what I entered on the console and looks good <><><><><><>
    Value of 80.a is: null <<<<<<<<<< I was hoping to get back TM value data "Question 80 Option A" from my tm.get <<<<<<<<<<<<<
    B4 Nested*The Key is: 80.a >>>>>>>> This looks Good but, is a variable (console entered value and not a TM key >>>>>>>>>>>>>>>
    The Value Key is: null <<<<<<<<<< I was expecting to get back: 80.a <<<<<<<<<<<<<
    The First Key is: 01.a,Question for 01? <<<<<<< I was expecting to get back: 01.a as the first TM key <<<<<<<<
    The FirstEntry is: 01.a,Question for 01?=01.a,Question for 01? <<<<<<<< "01.a,Question for 01?" is duplicated <<<<<<<<<<<<<<<
    The Last Key is: 80D.,Question 80 Option D <><><><><> This is the last record from INput file but, is not the key. It is the last TM entry <><><><>
    The LastKEntry is: 80D.,Question 80 Option D =80D.,Question 80 Option D <<<<< "80.D,Question 80 Option D is duplicated <<<<<
    The String Key is: null <<<<<<<<<< I was expecting to get the tm.get(id) key <<<<<<<<<<<<<<<<<<<<
    Number of Loaded Entries in tm.map is: 38

    Bottom Line: I was hoping to get this first Sorted record (as well as all the other records) loaded to TMap by key and value:
    Sorted 01.a,Question for 01?
    to have key tm.get(id) = 01.a
    and value tm.get(value) = Question for 01?
    ...
    to have key tm.get(id) = 80D.
    and value tm.get(value) = Question 80 Option D

    See more clearly by looking at "Entire Console Content" and find "Sorted"
    Attached Files Attached Files

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Did you try this: A suggestion for testing: Reduce the size of the input file to less than 10 lines. Say only 5 lines so that the printout will not be so long.

    For debugging, print out the value of tm so you can see what the key,value pairs are that have been saved in the TreeMap.

    What is the contents of the file that is being read? Are there separate fields on each line that need to be treated differently?

    Have you looked at the API doc for the TreeMap class to see what it does and how to use it?
    The code uses two of its methods: put and get
    Read the API doc for those methods to see what they do.

    Please don't post files that need to be downloaded and opened to be viewed. Post the console (reduced by the shorter input file) here on the thread so everyone can see it without having to download and open the file.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Yes. I actually reduced the file from hundreds of records to what I have now. Ok. I can easily reduce the file to 5 for now. Get the input key and value data separated so I can "PUT" is the big problem for me. Actually, I believe it is the only problem that I have. I have strings of panels that are easier to process than this. Panel after Panel flows very well. This PUT and Get have "Gotten" the best of me. Yes. A little PUN there. lol.

    I have been printing the contents of tm, or so I believe. Those are the printed displays prefixed with "Input".

    It's the sequential .txt file that is giving me problems. Hardcoding "Put" data in program is easy. "Get"ting is no problem either. Navigating is no problem either. Problem is when I replace the hardcoded "Put" and "Get" data with .txt file data that causes my problem. That is the confusion I have and, should not have. Conceptually, it is quite straight forward. I am certain if I ever get a resolution, that resolution will prove itself quite that simple.

    Content of the file is the same for each record: 1st 4 bytes(key), followed by a delimiter followed by the value data. I'll need the key to perform my get. No special processing for either of the two fields that I want.
    Ex:
    1st record: 01.a,Question for 01?
    should yield a TM Put like this: key: 01.a value data: Question for 01?
    2nd record: 01A.,Question 01 Option A
    should yield a TM Put like this: key: 01A. value data: Question 01 Option A

    Yes. I have looked at the API (often) and I believe that I have interpreted TreeMap to the best of my beginner Java skill set.
    Yes. I am using TM "put" and "get" in my program as well as FirstKey, FirstEntry, LastKey, LastEntry and have removed from my program several others. The Put and Get is my one (if not the only) problem with my program. I am not using them correctly in regards to a .txt input file. I know (or have a very good idea) of what I am doing when I hardcode the input data for my TM Put and Get in the program (got plenty of test examples and all work quite well, even with this data format that I have on my Chapt1Q.txt file). It's when I use a sequential file to do the same that is causing my problems.

    I have a very simple input file (three fields: key, delimiter and value data). That's it. What could be easier? I structured the file for that very reason. Keep it simple.
    Copy the 1st 4 bytes (only) of input data to TM Key.
    Copy bytes 6 to EOR (end of record) of input data to TM value.
    Put TM key and value.

    <Repeat till EOF>
    Should be Very simple.

    Ohhhh. I thought I was doing a good service by attaching files. Beginner mistake. My bad. Ok. Gotch-ya.

    Should I continue pasting the program and results in each Thread reply?

    **YOUR CODE GOES HERE**

    First : TMDemo program pasted
    Second: Input Chapt1Q.txt file (reduced to 5 records)
    Third : Complete Console Content

    TMDemo:
    import java.text.Collator;
    import java.util.Set;
    import java.io.*;                   // This has BufferedReader and more in it
    import java.util.TreeMap;           // This allows you to use TreeMap elements
    import java.util.*;                 // This allows you to use Scanner (find out more precise)
    //"C:\\Users\\Don\\Documents\\Chapt1Q.txt"
    /**
     * OverView:  TMapKey is not separated from TMapEntry for navigation purposes. 
     * This should be Very Easy (3 field Input File), Sort, Load TMap and "Get" TMapkey.
     *   Read UnSorted sequential text file in as Input and display Input recs.
     *      Text File Layout(fixed):  bytes 1=>4(key) byte5(delimeter) rest of file=(value)
     *   Sort, Put TMap and Display (sorts fine but, does not separate key, delimeter and value) 
     *      Because no separation of those 3 fields causes my TMap navigation to Fail. 
     *   Write Output Clean.txt file from Sorted records - this file is Sorted correctly "as is".
     *   Console entry (80.a) 
     *      Does not separate TMapKey from TMapEntry.  TMap "Get" does not work.
     *      This is my BIGGEST Problem.  
     *      
     *      I'd like to see TMapKey as a true key field not as Key+Delimeter+Value.  
     *      My TMapEntry is input record strung twice across.
     */
     
    public class TMDemo {
     // Removed most of my parameter passing = "C:\\Users\\Don\\Documents\\Chapt1Q.txt" broken down to:
     // For easier reviewing of meaningful code.
     private static String endOfLine         = "\n";
        private static String Subscr            = "1";
     
        /**
         * The main function.
         * @param args - Removed most to make code easier to read 
         */
        public static void main(String[] args) throws Exception {   
            String line                = null;
               System.out.println("Set String Line to null"); 
             BufferedReader fileReader = 
                new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Chapt1Q.txt"));
             System.out.println("     Just after BufferedReader : " +  fileReader);
           //* = new BufferedReader(new FileReader("C:\\Users\\Don\\Documents\\Chapt1Q.txt"));
             FileWriter fileWriter = new FileWriter("C:\\Users\\Don\\Documents\\clean.txt");
             System.out.println("     Just after FileWriter Defined : " +  fileWriter);
           {
         /**
          * The tree_map defined.
          */
        TreeMap<String, String> tm = new TreeMap<String, String>();  // take out >() That made no diff
     
             System.out.println(" Start sorting/looping Input here using - display Once");
                while((line = fileReader.readLine()) != null)    // Loops Read for each Chapt1Q record
            {   
                  tm.put(line, line);   //   Load the tree_map
     
                System.out.println("Input  " + tm);   //Prints each Chapt1Q rec Unsorted (key&value as one)
     
        }
            fileReader.close();
               System.out.println("fileReader.close and Loop Writing each Sorted Chapt1Q rec to Clean.txt");     
         for (String keyin : tm.values()) {   // For Each Loop=> Writes the Sorted Chapt1Q file    
                                          // to output Clean.txt file
                fileWriter.write(keyin + endOfLine);
                              // // Prints each Sorted Chapt1Q.  If you add + end0fLine gets a 
                              // lot of wrap around non printable data 3 lines worth.
                  System.out.println("Sorted  " +keyin);  
     
        }
     
            fileWriter.close();             // This is the end of Clean.txt Writes (output file)
           // Displaying the TreeMap 
           System.out.println("Initial Mappings are: " + tm); 
           System.out.println(" Select a Search key : ");  // prints after 
           //System.out.println("Value of "+QKey+" is: "+tree_map.get(keyin)); 
           Scanner console = new Scanner(System.in);
           String QKey = console.next();            // Is my entry for Search Key  use: 80a.
     
           System.out.println("Value of "+QKey+" is: "+tm.get(QKey)); 
           // Getting the value of selected key in println get
           // I have not yet figured out how to get the key with the first 4 char's ex: "80.a"
            String id = QKey;
            System.out.println("B4  Nested*The Key   is: " + id); 
     
            if (tm.containsKey(id)){
               //** Keep        if (tm.containsKey("80.a")) {
              System.out.println("*Nested*The keySetis: " + tm.keySet());
     
              System.out.println("*Nested*The Key   is: " + id); 
           // Getting the value of selected key 
            System.out.println("*Nested*The IDVal is: " + tm.get(id));
            System.out.println("*Nested*The Value is: " + tm.get("80.a"));  
        }
            System.out.println("The Value  Key is: " + tm.get(id)); //returns null if no Higher
            System.out.println("The First  Key is: " + tm.firstKey()); //returns null if no Higher
            System.out.println("The FirstEntry is: " + tm.firstEntry()); //returns null if no Higher
            System.out.println("The Last   Key is: " + tm.lastKey()); //returns null if no Higher
            System.out.println("The LastKEntry is: " + tm.lastEntry()); //returns null if no Higher
     
            String element1 = (String) tm.get(id);
            //  String element1 = (String) tm.get("01.a");
                    System.out.println("The String Key is: " + element1);
     
        int entryCount = tm.size();  
                      System.out.println("Number of Loaded Entries in tm.map is: " + entryCount);
        }
    }
    }


    Input Chapt1Q.txt file (reduced to 5 records) and unSorted
    02.a,Question for 02?
    01A.,Question 01 Option A
    01.a,Question for 01?
    03A.,Question 03 Option A
    03.a,Question for 03?


    Complete Console Content
    Set String Line to null
         Just after BufferedReader : java.io.BufferedReader@12d583c
         Just after FileWriter Defined : java.io.FileWriter@14d0fad
     Start sorting/looping Input here using - display Once              <><><><><   Also performs "Put"(s) on each "Input " record   <><<><><>
    Input  {02.a,Question for 02?=02.a,Question for 02?}
    Input  {01A.,Question 01 Option A=01A.,Question 01 Option A, 02.a,Question for 02?=02.a,Question for 02?}
    Input  {01.a,Question for 01?=01.a,Question for 01?, 01A.,Question 01 Option A=01A.,Question 01 Option A, 02.a,Question for 02?=02.a,Question for 02?}
    Input  {01.a,Question for 01?=01.a,Question for 01?, 01A.,Question 01 Option A=01A.,Question 01 Option A, 02.a,Question for 02?=02.a,Question for 02?, 03A.,Question 03 Option A=03A.,Question 03 Option A}
    Input  {01.a,Question for 01?=01.a,Question for 01?, 01A.,Question 01 Option A=01A.,Question 01 Option A, 02.a,Question for 02?=02.a,Question for 02?, 03.a,Question for 03?=03.a,Question for 03?, 03A.,Question 03 Option A=03A.,Question 03 Option A}
    fileReader.close and Loop Writing each Sorted Chapt1Q rec to Clean.txt
    Sorted  01.a,Question for 01?                              <><><> Begins the writing to output file in Sorted order  <><><>
    Sorted  01A.,Question 01 Option A
    Sorted  02.a,Question for 02?
    Sorted  03.a,Question for 03?
    Sorted  03A.,Question 03 Option A
    Initial Mappings are: {01.a,Question for 01?=01.a,Question for 01?, 01A.,Question 01 Option A=01A.,Question 01 Option A, 02.a,Question for 02?=02.a,Question for 02?, 03.a,Question for 03?=03.a,Question for 03?, 03A.,Question 03 Option A=03A.,Question 03 Option A}
     Select a Search key : 
    02.a                           Console Entered value as this 02.a key is / should be in the middle of the TMap
    Value of 02.a is: null
    B4  Nested*The Key   is: 02.a                <<>> Simply displays the key that I entered after moving it to a variable  <<>> 
    The Value  Key is: null                      <<<<  Not value retrieved as I apparently did not perform my Put correctly   <<<<<<<<<
    The First  Key is: 01.a,Question for 01?    <<<<<   Got the first Tmap Entry not the TMap key  >>>>>
    The FirstEntry is: 01.a,Question for 01?=01.a,Question for 01?     <<<<  Got the last Entry correctly but is duplicated  <<<<<<<<<
    The Last   Key is: 03A.,Question 03 Option A     <<<<<   Got the first Tmap Entry not the TMap key  >>>>>
    The LastKEntry is: 03A.,Question 03 Option A=03A.,Question 03 Option A     <<<<  Got the last Entry correctly but is duplicated  <<<<<<<<<
    The String Key is: null       <<<<<<  Suppose to be the value in (String) tm.get(id) which appears to be null   <<<<<<<<<<<<<<<<
    Number of Loaded Entries in tm.map is: 5

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    I have been printing the contents of tm
    It could be done outside the loop to make for fewer printed lines. The label for the output could be tm= instead of Input.
    The print out shows the key's value before the = and the value afterwards up to the comma that separates the key=value pairs:
    01.a,Question for 01?=01.a,Question for 01?,....
    simple input file (three fields: key, delimiter and value data)
    The code needs to separate the contents of the line variable into the key and the value so they can be used in the put method.
    Right now the value of line is used both for the key and for the value. That makes no sense.
    The String class has several methods for separating a String into parts. See the substring and the split methods.

    Separating the key and value is the next step. Try writing a small, simple program that takes the String:
      String line = "01.a,Question for 01?";
    and separates it into a key String and a value String.
    When that works, copy the logic into the main program.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Haaaaahhhhh. You area an early Eastern US lad as is myself. Been up since 4 myself.

    Btw- thanks for the "Code tag" example. What a BIG difference that made.

    Re: your post - Exactly!! That is what I have been trying to say from the first post.
    My problem resides in this bit of code (and Yes, it does not make any sense to me; hence, why my head hurts so badly. (my key is a combination of char's and integers; thus, I went with "String"). I have tried so many combinations, concepts, etc.
        TreeMap<String, String> tm = new TreeMap<String, String>();  // take out >() That made no diff
     
             System.out.println(" Start sorting/looping Input here using - display Once");
                while((line = fileReader.readLine()) != null)    // Loops Read for each Chapt1Q record
            {   
                  tm.put(line, line);   //   Load the tree_map
     
                System.out.println("Input  " + tm);   //Prints each Chapt1Q rec Unsorted (key&value as one)
     
        }
            fileReader.close();

    Summary: Record has two Input variables separated by a delimiter, copy/move/whatever to TMkey and TMvalue and wholahhh. Done. That is what I meant by being easy. Hard Coded data in the program (see my "Simple HardCoded... ex below) is easy but, boy is this read .txt file and load to TMap kicking my butt.

    I'll give those "Similar Threads" and your suggestion a try in a small program that I started a few days ago and see if I can make sense of the process.

    History - I took a 6 week online course a while ago. It was ok. My father passed away during that time and I never got into a rythym with the class (I was in a constant catch up mode). Having said that - do you have any books, online reads, references, etc. that you think might be helpful in filling a plethora of voids I have with Java? I almost bought one book on Amazon and when I got the ebook temp version I realized it had little to NOthing on TMaps so I cancelled the order. In addition: I do not know much about compile assistance and API - I find API is difficult to interpret. So, basically - I have no references. Wasted way too much time on the Internet searching (Most if not all were Integer based - I know, concept is the same).
    API TreeMap - "put"
    put
    [B]public V put(K key,
                 V value)[/B]               [U]<<<<  Interpretted as:  (two keys and two values?) or  (Type of key and key's value? & Type of val and val's value??)[/U]
    Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
    Specified by:
    put in interface Map<K,V>
    Overrides:
    put in class AbstractMap<K,V>
    Parameters:
    key - key with which the specified value is to be associated
    value - value to be associated with the specified key

    If you have a moment: How do I interpret the API definition above to this simple program of mine below?

    Example of one of my Simple HardCoded TMap put objects and this one, I took out a "replace" action and the program replaces the value fine. So, HardCoded data is not a problem for me at this level.

          // creating tree map 
          TreeMap<Integer, String> TMap = new TreeMap<Integer, String>();
     
          // populating tree map
          TMap.put(2, "two");
          TMap.put(1, "one");
          TMap.put(3, "three");
          TMap.put(6, "six");
          TMap.put(5, "five");   
    ....

    Notice: NO Attachments - TY

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Have you tried writing a small, simple program as I suggested earlier:

    Separating the key and value is the next step. Try writing a small, simple program that takes the String:
      String line = "01.a,Question for 01?";
    and separates it into a key String and a value String.
    When that works, copy the logic into the main program.

    The tutorial has lots of descriptions of java programming. Here is a link to a page with lots of topics:
    http://docs.oracle.com/javase/tutori...ybigindex.html

    public class TreeMap<K,V>
    The TreeMap class's API doc uses generics to describe its syntax. The K and V are variables are replaced by the actual data type when the program uses the class. For example with the following statement:
    TreeMap<String, String> tm =
    The value of K is set to String and the value of V is set to String.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Yes, I am working on the small program. Trust me. I want/NEED to wrap this up for my Sanity as I think I have lost it somewhere.
    I am also looking at the API for String class and Sub and Split methods as you suggested as well.

    The examples URL you suggested no longer exists (bummer). A picture is worth a thousand words, right? LOL.
    http://docs.oracle.com/javase/tutori...ybigindex.html

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    The examples URL you suggested no longer exists
    It is there, just click on the displayed link, don't copy and paste it because the forum's software has shortened it and inserted ... into the middle of the URL.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Feb 2019
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Quote Originally Posted by Norm View Post
    It is there, just click on the displayed link, don't copy and paste it because the forum's software has shortened it and inserted ... into the middle of the URL.
    Sorry for the delay in responding - I got Black Screened and lost my computer for a while (90 minutes or more). Never happened to me before. Boy was I scared!!!

    Yes, the link is there. I have not looked at it yet as I was looking at another site re: subString. "Spot On"!!! TY

    Once I added the String & subString to my BReader (BufferedReader) then everything else came together for the most part. TreeMap is working fine and Navigating. All others: Read, Sort, Put, Write, Get and ohhhhh yes, and the closes are all fine - or appear to be. I have more reviewing to do before I feel comfortable enough to move on.

    Ohhhhh - I now have many String and subString examples (small programs) that I have created and have been playing with the String Class ever since. Picture (one working example) is worth a thousand words.

    My Simple Problem had in fact a Simple Answer it appears.

    ?? Are these threads between you and myself in a/or part of a Forum?
    Again, I am new to Java and Forums.
    I could use a good reference (book or other).

    Also, since my projects will be small in nature... am I missing out on anything that NetBeans, Eclipse, etc. have that would help me with compile errors. Thus far, I have been trying to interpret what little assistance BlueJ gives me.

    Btw- Once I am done with this personal project (panels, programs, etc) I plan on experimenting further. Load my .txt file to a database, etc. If my data is on a database I am guessing that I would no longer need a TreeMap. You agree?

    I a way, I am glad you did not simply give me a resolution to my problem. A few pointers along the way would have helped but, the thread(s) on SubString/Split was HUGE!!!

    Finally, I have noticed that you had a number of posts, thankyou's, etc. How do I give you a TY?

    Sorry, I ask a lot of questions. I will reduce them starting now. I have enough to keep me busy.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,325
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: Text file load to TreeMap Get Problem. Should be Very Easy to correct BUT, I am very New to Java

    Glad you got this project working.
    Now on to the next one.

    This is a public thread.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Java code Split text file into multiple text file
    By jayraj in forum What's Wrong With My Code?
    Replies: 26
    Last Post: April 19th, 2013, 06:14 AM
  2. how do i load my text file into my jtable.
    By legend101z in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: April 6th, 2013, 02:23 PM
  3. Replies: 2
    Last Post: September 27th, 2012, 07:06 PM
  4. How to up load java file when you post??
    By zhen1606 in forum Collections and Generics
    Replies: 1
    Last Post: February 23rd, 2012, 08:12 AM
  5. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM