Results 1 to 20 of 20
  1. #1
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default Printing contents of Arraylist -- strange issue

    First of all, let me say yes this is for a class at school. Sorry if that is an issue for you, I am only trying to learn what I have done wrong. I do not expect you to do any work for me, and really appreciate any time you can give.

    This is the first time I have used an Arraylist, so you may look at some of the things I have done, and wonder wtf is going on, sorry about that. 1 requirement is that I have an external file with a class that defines 3 variables. Here is that class.

    "external class with variables"
    Java Code:
    public class Student {
     String name;
     double gpa;
     int hrsPassed;
    }
    Here is my main program, you will see that I have some "System.out.println" through out, these are only to test my data. All data is supposed to go to a file. The System.out is where I have found the problem however, which I will show toward the end of the post.

    Java Code:
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import java.lang.*;
    
    public class Program12 {
    
    public static void main(String[] args) throws Exception
       {
        Scanner inFile = new Scanner (new FileReader("H:/Metro/NetBeansProjects" +
                                     "/CS1050/data/12in.dat"));
        PrintWriter outFile = new PrintWriter("H:/Metro/NetBeansProjects" +
                                     "/CS1050/data/12out.dat");
        ArrayList list = new ArrayList();
        int count=0;
    
        count = fillArray(list, count, inFile, outFile);
        gpaMethod(list, count, outFile);
    
        outFile.close();
       }
    //******************************************************************************
    public static int fillArray(ArrayList list, int count,
                                Scanner inFile, PrintWriter outFile)
    {
      String tempData=null, tempName, line, s;
      char letter;
      StringTokenizer st, str;
      int i=0,number, gpaSwitch=0, credits=0;
      double pairsLength=0, gpaCalc;
    
         outFile.println("Data Echo:");
         outFile.println("==========");
         while(inFile.hasNext())
          { 
            gpaCalc=0;
            line = inFile.nextLine();
            st = new StringTokenizer(line);
            tempName = st.nextToken("#");
            
            Student studMuffin = new Student();
            tempData = st.nextToken("#");
            //data echo
            outFile.println(tempName + "#" + tempData + "#");
            str = new StringTokenizer(tempData);
    
            //determine that there is at least one pair of data
             pairsLength = trimRight(trimLeft(tempData)).length();
    
            //data process and store in ArrayList
            while(str.hasMoreTokens() &&  pairsLength>=3)
             {
             number = Integer.parseInt(str.nextToken());
             letter = str.nextToken().charAt(0);
             gpaSwitch=Character.getNumericValue(letter);
              
               switch (gpaSwitch)
               {
                  case 10:
                          credits += number; //credit for A;
                          gpaCalc += 4 * number; //4 points for A
                          break;
                  case 11:
                          credits += number; //credit for B;
                          gpaCalc += 3 * number; //3 points for B
                          break;
                  case 12:
                          credits += number; //credit for C;
                          gpaCalc += 2 * number; //2 points for C
                          break;
                  case 13:
                          credits += number; //credit for D;
                          gpaCalc += 1 * number; //1 point for D
                          break;
                  case 15:
                          credits += 0; //no credit for F
                          gpaCalc += 0; //no points for F
                          break;
                  case 28:
                          credits += number; //credit for S;
                          break;
                  default:
                          credits += 0; //grade not recognized
                          gpaCalc += 0; //grade not recognized
                          
               }
             }
           studMuffin.name = trimLeft(trimRight(tempName));
           studMuffin.gpa = gpaCalc/credits;
           studMuffin.hrsPassed = credits;
    
           System.out.println("Name: " + studMuffin.name);
           System.out.println("GPA: " + studMuffin.gpa);
           System.out.println("Credits: " + studMuffin.hrsPassed);
    
           list.add(studMuffin);
           i++;
           }
      outFile.println("===================================================");
    
    
      return i;
    }
    //******************************************************************************
    public static void gpaMethod(ArrayList list, int count,
                                PrintWriter outFile)
    {   Iterator i1 = list.iterator();
    
        while (i1.hasNext())
        {
    	System.out.print(i1.next() + " , ");
        }
        
    }
    //******************************************************************************
    private static String trimRight(String data)
    {
     int index = data.length()-1;
      if (index >= 0)
      {
        while (data.charAt(index) == ' ')
        {
          index--;
        }
     
        if (index < 0)
        {
          return "";
        } 
        else 
        {
          return data.substring(0,index+1);
        }
      }
      else 
      {
       return data;
      }
     }//end of trimRight(String name)
    //******************************************************************************
    private static String trimLeft(String data)
    {
     int index = 0;
    
     if (data == null)
         return "";
    
     while (data.charAt(index) == ' ')
        {
          data = data.substring(1);
        }
     return data;
    }//end of trimLeft(String name)
    
    }
    Here is the output. You will see that my assignment of the name, gpa, and credit amount seems to be looking good, as far as the fillArray method is concerned...
    Java Code:
           System.out.println("Name: " + studMuffin.name);
           System.out.println("GPA: " + studMuffin.gpa);
           System.out.println("Credits: " + studMuffin.hrsPassed);
    followed by "gpaMethod" output:
    Java Code:
    Iterator i1 = list.iterator();
    
        while (i1.hasNext())
        {
    	System.out.print(i1.next() + " , ");
        }
    However, just the simple gpaMethod method is giving me what I would not expect to be in the Arraylist. Can anyone tell me what I have done wrong?

    Output(System.out ONLY):
    Java Code:
    Name: Van Zell David
    GPA: 2.0
    Credits: 8
    Name: Toole Nancy
    GPA: 2.1578947368421053
    Credits: 19
    Name: Tucker Henry
    GPA: 0.20833333333333334
    Credits: 24
    Name: Van Zell Sally
    GPA: 0.4117647058823529
    Credits: 34
    Name: Tucker Becky
    GPA: 1.2244897959183674
    Credits: 49
    Name: Stratton Charles
    GPA: 0.2857142857142857
    Credits: 63
    Name: Toole Charles
    GPA: 0.0
    Credits: 63
    Name: Thomas William
    GPA: 0.5066666666666667
    Credits: 75
    Student@14318bb , Student@ca0b6 , Student@10b30a7 , Student@1a758cb , Student@1b67f74 , Student@69b332 , Student@173a10f , Student@530daa ,
    Question:
    What is going on with this "Student@..." That is not what I thought I put into the Arraylist...


    Input file (if you care)
    Java Code:
    Van Zell David          # 4 D 4 B #
    Toole Nancy             # 3 A 3 B 5 A 4 X #
    Tucker Henry            # 5 D 3 F 2 U 4 F #
    Van Zell Sally          # 4 C 6 D #
    Tucker Becky            # 3 A 3 A 2 A 4 A 3 A #
    Stratton Charles        # 2 S 2 D 5 C 4 D 1 C #
    Toole Charles           # 3 U #
    Thomas William          # 4 A 3 B 2 C 3 B #
    Thank you to anyone willing to take a couple minutes to look at this. :o

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    Hi there, no problem if this is a school assignment, as long as you do the work and post a specific question as you did. In your sysouts you print the attributes of your Student class
    Java Code:
     System.out.println("Name: " + studMuffin.name);
    This works fine, but in gpa you print out the String representation of Student, that's like
    Java Code:
    System.out.println(studMuffin);
    Your options are to override toString() in Student or to create another method that returns a String representation of your Student object.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,420
    Rep Power
    25

    Default

    Further explanation.
    Student@ca0b6 is what is returned by the Object toString() method. Its the class name followed by its memory location.
    As PhHein said: If you want to see info about your class you need to override the toString() method to return what you'd like to see.

  4. #4
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    Thank you! I just wrote a HUGE response and must have timed out. I am working on it on my machine and will post in just a second.

  5. #5
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by PhHein View Post
    Hi there, no problem if this is a school assignment, as long as you do the work and post a specific question as you did. In your sysouts you print the attributes of your Student class
    Java Code:
     System.out.println("Name: " + studMuffin.name);
    This works fine, but in gpa you print out the String representation of Student, that's like
    Java Code:
    System.out.println(studMuffin);
    Your options are to override toString() in Student or to create another method that returns a String representation of your Student object.
    Now, wouldnt I need to put this into some kind of for or while loop and reference index numbers or something so I can bring out the entire Arraylist? Or is the way I am filling it going to overwrite it self every time?


    If I stick a: System.out.println (list.size()); in the main method right after the call to the fillArray method, it will return the proper amount, 8 "students".

    I keep wanting to print it like a regular array... studMuffin.name[1] and so on.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,420
    Rep Power
    25

    Default

    Not sure what all your questions are.
    The ArrayList class has methods that allow you to retrieve elements based on an index, like you can do with an array. You use a method call vs using the array reference: []

  7. #7
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Not sure what all your questions are.
    The ArrayList class has methods that allow you to retrieve elements based on an index, like you can do with an array. You use a method call vs using the array reference: []
    Well, I guess my thought is, by printing only studMuffin.name, you are really just printing a string from another class, not something that is stored in an Arraylist.

    Is that correct, or incorrect?

    Also, If I have multiple studMuffins in the Arraylist "list" how do I roll though and print each out?

    System.out.println(studMuffin); only gets me Class name with memory address.

    Edit: maybe this will help. I have to have the student name, gpa, and total credits in the array list (variables in the Student class)

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,420
    Rep Power
    25

    Default

    by printing only studMuffin.name, you are really just printing a string from another class
    yes, only the contents of the studMuffin object

    If I have multiple studMuffins in the Arraylist "list" how do I roll though and print each out?
    use the get method to retrieve each element to process

    System.out.println(studMuffin); only gets me Class name with memory address.
    See the above posts about adding: public String toString() { return what you want to see here}
    Last edited by Norm; 08-09-2010 at 05:33 PM.

  9. #9
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    "I see" said the blind man. Working on this now.

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Quote Originally Posted by Norm View Post
    Further explanation.
    Student@ca0b6 is what is returned by the Object toString() method. Its the class name followed by its memory location.
    <pedant_mode>It's the classname and hashcode.</pedant_mode>

    ETA: Just to clarify, I don't think there's anything that says it's the memory address.

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,420
    Rep Power
    25

    Default

    The API doc says:
    This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required ...

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    "not required".
    On top of which, hashCode() is more often overridden than toString().

    I did say <pedant>...:)

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,420
    Rep Power
    25

    Default

    Ok, why pick at nits.

    BTW FWIT I've overridden toString() 100 times more than hashCode()

  14. #14
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    I suppose I could rewrite toString(). However, I would be really surprised if that is what she is wanting us to do. Is that the only way to pull data from the Arraylist?

  15. #15
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    No for god's sake, you've successfully pulled the data from the arraylist. You just don't do the same things to print the information. Read my previous post.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  16. #16
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by PhHein View Post
    No for god's sake, you've successfully pulled the data from the arraylist. You just don't do the same things to print the information. Read my previous post.
    Wow, so much hostility. :eek:

    I am sorry that I don't understand it as well as you do. I will do my best to figure it out using your previous post.

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by YeeP View Post
    Wow, so much hostility. :eek:
    No hostility; it's more like despair.

    kind regards,

    Jos

  18. #18
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    There was no hostility whatsoever, but you've never posted a different attempt which considers the replies you've been given.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  19. #19
    YeeP is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by PhHein View Post
    There was no hostility whatsoever, but you've never posted a different attempt which considers the replies you've been given.
    You are right, I did try what I thought you where saying and I was doing it wrong. I did not want to post everything I was doing and waste your time. I am sorry.

    Quote Originally Posted by PhHein
    String representation of your Student object.
    That got me thinking, I know I can print it as a class object. So, I made a for loop, and it seems to be working. Here is what I did to solve the problem of printing. The method is not done yet, but the printing is working and I wanted to show you.
    Java Code:
    public static void gpaMethod(ArrayList list, int count,
                                PrintWriter outFile)
    {   
       for(int i=0; i<list.size();i++)
       {
          Student S = (Student)list.get(i);
          System.out.println("gpaMethod");
          System.out.println("==========");
          System.out.println("Name: " + S.name);
          System.out.println("GPA: " + S.gpa);
          System.out.println("Credits: " + S.hrsPassed);
       }
    }
    I also tweaked the output in the fillArray method, just so I would know on the System.out side that all was well...
    Java Code:
           System.out.println("fillArray");
           System.out.println("=========");
           System.out.println("Name: " + studMuffin.name);
           System.out.println("GPA: " + studMuffin.gpa);
           System.out.println("Credits: " + studMuffin.hrsPassed);
    Here is the output:
    Java Code:
    fillArray
    =========
    Name: Van Zell David
    GPA: 2.0
    Credits: 8
    fillArray
    =========
    Name: Toole Nancy
    GPA: 2.1578947368421053
    Credits: 19
    fillArray
    =========
    Name: Tucker Henry
    GPA: 0.20833333333333334
    Credits: 24
    fillArray
    =========
    Name: Van Zell Sally
    GPA: 0.4117647058823529
    Credits: 34
    fillArray
    =========
    Name: Tucker Becky
    GPA: 1.2244897959183674
    Credits: 49
    fillArray
    =========
    Name: Stratton Charles
    GPA: 0.2857142857142857
    Credits: 63
    fillArray
    =========
    Name: Toole Charles
    GPA: 0.0
    Credits: 63
    fillArray
    =========
    Name: Thomas William
    GPA: 0.5066666666666667
    Credits: 75
    gpaMethod
    ==========
    Name: Van Zell David
    GPA: 2.0
    Credits: 8
    gpaMethod
    ==========
    Name: Toole Nancy
    GPA: 2.1578947368421053
    Credits: 19
    gpaMethod
    ==========
    Name: Tucker Henry
    GPA: 0.20833333333333334
    Credits: 24
    gpaMethod
    ==========
    Name: Van Zell Sally
    GPA: 0.4117647058823529
    Credits: 34
    gpaMethod
    ==========
    Name: Tucker Becky
    GPA: 1.2244897959183674
    Credits: 49
    gpaMethod
    ==========
    Name: Stratton Charles
    GPA: 0.2857142857142857
    Credits: 63
    gpaMethod
    ==========
    Name: Toole Charles
    GPA: 0.0
    Credits: 63
    gpaMethod
    ==========
    Name: Thomas William
    GPA: 0.5066666666666667
    Credits: 75
    Thank you to everyone for your help, I really appreciate that. ;) :cool:

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Quote Originally Posted by Norm View Post
    Ok, why pick at nits.
    This is the internet, isn't that what it's for? Pointless discussion about minutiae?
    :D

    Quote Originally Posted by Norm View Post
    BTW FWIT I've overridden toString() 100 times more than hashCode()
    Ah, the stuff I tend to work on usually involves object comparisons, so equals() is almost always written, and consequently so is hashCode(). But output is less of a problem.

Similar Threads

  1. Replies: 3
    Last Post: 12-03-2009, 10:05 PM
  2. ArrayList printing
    By tommyyyy in forum New To Java
    Replies: 4
    Last Post: 03-20-2009, 04:33 AM
  3. Printing the contents of an array of objects
    By Mr.Paplu in forum New To Java
    Replies: 1
    Last Post: 03-19-2009, 04:49 PM
  4. Issue with printing line
    By Azndaddy in forum Advanced Java
    Replies: 1
    Last Post: 04-04-2008, 07:37 PM
  5. Printing contents of a web page
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-26-2007, 12:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •