Results 1 to 8 of 8
  1. #1
    cbrown08 is offline Member
    Join Date
    Oct 2007
    Posts
    4
    Rep Power
    0

    Default Understanding Vectors

    I do not quite understand vectors regardless of how many pages I read on them, I have been assigned this program in my java class, I have written the following code so far, some of it was given to me, such as the v.add(cr) in the student class, however I have no clue as to what exactly is in my vector, where it is, and how to pull the variables that I need from it, which is what I ultimately need to do. If someone could please shed some light and point me in the right direction I would appreciate it. I have three classes, gradebook(supplies a gui with 3 buttons, one of which adds a student who has characteristics and up to 5 courses, one button which is supposed to print everything about the students(which is nowhere near done yet, don't worry about that), and one just to exit. Here's my code.

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
     
    public class Gradebook extends JFrame 
    {
    private Button add;
    private Button print;
    private Button exit;
    float[] gpa_array=new float[5];
    private int num_students=0;
    Student[] stu=new Student[5];
     
    public Gradebook()
    {
    super("Student/Course GUI");
    for(int a=0;a<5;a++)
    stu[a]=new Student();
    ButtonHandler handler = new ButtonHandler();
    Container cat = getContentPane();
    cat.setLayout(new FlowLayout());
    add = new Button("Add Student");
    add.addActionListener(handler);
    cat.add(add);
    print = new Button("Print");
    print.addActionListener(handler);
    cat.add(print);
    exit = new Button("Exit");
    exit.addActionListener(handler);
    cat.add(exit);
    setSize(800,600);
    setVisible(true);
    }
    public class ButtonHandler implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
    {
    if(e.getSource()== add)
    {
    num_students++;
    stu[num_students].getData();
    }
    else
    if(e.getSource() == print)
    System.out.println("Printing all courses and students");
    else
    if(e.getSource() == exit)
    System.exit(0);
    }
    }
     
    public static void main(String[] args)
    {
    Gradebook app = new Gradebook();
    }
    }
    
    
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Vector;
    public class Student
    {
    private String name;
    private String stringage;
    private int age;
    private float gpa;
    private int num_courses;
    private String stringnum_courses;
    private int totalqp;
    private Vector v = new Vector();
        public Student()
        {      
        }
     
    public void getData()
    {
    name = JOptionPane.showInputDialog(null,"Enter Student's Name","Enter Student's Name", JOptionPane.QUESTION_MESSAGE);
    stringage = JOptionPane.showInputDialog(null,"Enter Student's Age","Enter Student's Age", JOptionPane.QUESTION_MESSAGE);
    age = Integer.parseInt(stringage);
    stringnum_courses = JOptionPane.showInputDialog(null,"Enter Number of Courses","Enter Number of Courses", JOptionPane.QUESTION_MESSAGE);
    num_courses = Integer.parseInt(stringnum_courses);    
    for(int a=0;a<num_courses;a++)
    {
    Course cr = new Course();
    v.add(cr);
    }
    }
    }
    
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class Course
    {
        // instance variables - replace the example below with your own
        private int id;
        private String dept;
        private int credits;
        private String letter_grade;
        private String stringid;
        private String stringcredits;
        private int QP;
        public Course()
        {
         getDept();
         getId();
         getCredits();
         getLettergrade();
         getQP();
        }
     
        public void getDept()
        {
           dept = JOptionPane.showInputDialog(null,"Enter Department","Enter Department", JOptionPane.QUESTION_MESSAGE); 
    }
    public void getId()
    {
    stringid = JOptionPane.showInputDialog(null,"Enter Course ID","Enter Course ID", JOptionPane.QUESTION_MESSAGE); 
    id = Integer.parseInt(stringid);
    }
    public void getCredits()
    {
    stringcredits = JOptionPane.showInputDialog(null,"Enter Credits","Enter Credits", JOptionPane.QUESTION_MESSAGE); 
    credits = Integer.parseInt(stringcredits);
    }
    public void getLettergrade()
    {
    letter_grade = JOptionPane.showInputDialog(null,"Enter Letter Grade","Enter Letter Grade", JOptionPane.QUESTION_MESSAGE); 
    }
    public void getQP()
    {
    if(letter_grade=="A")
    QP=4*credits;
    if(letter_grade=="B")
    QP=3*credits;
    if(letter_grade=="C")
    QP=2*credits;
    if(letter_grade=="D")
    QP=credits;
    if(letter_grade=="F")
    QP=0;
    }
    }
    Here is the exact assignment just for any clarification purposes:
    3 classes
    Course
    Student
    Gradebook(main)

    The Main class will have 3 Buttons to control the following Events:

    1...Add student to system (initial data--name, gender, and course load (1 to
    5 courses))
    A Vector in the student class will be initially set to 5 courses for
    each of 5 possible students
    An array in the Gradebook class will hold references to each of the 5
    student objects

    2...Print all student data (along with gpa) High to low based upon gpa.

    3...Exit
    Last edited by cbrown08; 10-31-2007 at 09:59 AM.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Vector is a legacy class and has been retrofitted to work in the Collections framework that came out in j2se 1.2
    Look up the Vector class api in the javadocs to see what methods and fields are available for you to use. Here's a link into the javadocs for version 1.5 1.5 javadocs. Scroll down to the Vector class in the lower left frame, select the link and the Vector class api loads into the main frame.
    Since you are using Vector you may also be using an older java version. Type "java -version" at the prompt to find out. If you are using j2se 1.5 or later you can use the generic declarations shown (but this is not required). If you are using an older version (1.4 of earlier) you can forget about generics but will have to make a cast (shown below) when taking each Course out of the vector. You can make the cast in generics, too if you want but it is not required.
    This is currently set up for generics so you'll have to comment/uncomment the appropriate (marked) options to get this to compile if you are using an earlier version.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    
    public class GradebookRx extends JFrame 
    {
        private JButton add;
        private JButton print;
        private JButton exit;
        float[] gpa_array=new float[5];
        private int num_students=0;
        Student[] stu=new Student[5];
        JTextArea textArea = new JTextArea();
     
        public GradebookRx()
        {
            super("Student/Course GUI");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            for(int a=0;a<5;a++)
                stu[a]=new Student();
            // Initialize buttons
            ButtonHandler handler = new ButtonHandler();
            JPanel north = new JPanel();
            add = new JButton("Add Student");
            add.addActionListener(handler);
            north.add(add);
            print = new JButton("Print");
            print.addActionListener(handler);
            north.add(print);
            exit = new JButton("Exit");
            exit.addActionListener(handler);
            north.add(exit);
            Container cat = getContentPane();
            cat.add(north, BorderLayout.NORTH);
            cat.add(new JScrollPane(textArea)); // default center section
            setSize(800,600);
            setLocation(100,100);
            setVisible(true);
        }
    
        public class ButtonHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                JButton button = (JButton)e.getSource();
                if(button == add)
                {
                    num_students++;
                    stu[num_students].getData();
                }
                else if(button == print)
                {
                    System.out.println("Printing all courses and students");
                    printAllData();
                } else if(button == exit)
                    System.exit(0);
            }
        }
    
        private void printAllData()
        {
            textArea.setText("");
            for(int j = 0; j < stu.length; j++)
            {
                if(stu[j].getName() != null)  // no empty student elements
                {
                    textArea.append(stu[j] + "\n");
                    printCourseData(stu[j].getVector());
                }
            }
        }
    
        private void printCourseData(Vector<Course> v)    // generic method signature
        // private void printStudentData(Vector v)        //  non-generic signature
        {
            for(int j = 0; j < v.size(); j++)
            {
                Course course = v.get(j);                 // generic form
                //Course course = (Course)v.get(j);       // non-generic cast
                textArea.append(course + "\n");
            }
        }
     
        public static void main(String[] args)
        {
            new GradebookRx();
        }
    }
    
    class Student
    {
        private String name;
        private String stringage;
        private int age;
        private float gpa;
        private int num_courses;
        private String stringnum_courses;
        private int totalqp;
        // generic declaration for j2se 1.5+
        private Vector<Course> v = new Vector<Course>();
        // non-generic declaration for j2se 1.4-
        //private Vector v = new Vector();
    
        public Student() { }
     
        public void getData()
        {
            name = JOptionPane.showInputDialog(null,"Enter Student's Name",
                                               "Enter Student's Name",
                                               JOptionPane.QUESTION_MESSAGE);
            stringage = JOptionPane.showInputDialog(null,"Enter Student's Age",
                                                    "Enter Student's Age",
                                                    JOptionPane.QUESTION_MESSAGE);
            age = Integer.parseInt(stringage);
            stringnum_courses = JOptionPane.showInputDialog(null,"Enter Number of Courses",
                                                            "Enter Number of Courses",
                                                            JOptionPane.QUESTION_MESSAGE);
            num_courses = Integer.parseInt(stringnum_courses);    
            for(int a=0;a<num_courses;a++)
            {
                Course cr = new Course();
                v.add(cr);
            }
        }
    
        public String toString()
        {
            return "Name:" + name + " age:" + age +
                   " num_courses:" + num_courses;
        }
    
        public String getName()
        {
            return name;
        }
    
        public Vector<Course> getVector()    // generic method signature
        //public Vector getVector()          // non-generic signature
        {
            return v;
        }
    }
    
    class Course
    {
        // instance variables - replace the example below with your own
        private int id;
        private String dept;
        private int credits;
        private String letter_grade;
        private String stringid;
        private String stringcredits;
        private int QP;
    
        public Course()
        {
            getDept();
            getId();
            getCredits();
            getLettergrade();
            getQP();
        }
     
        public void getDept()
        {
            dept = JOptionPane.showInputDialog(null,"Enter Department","Enter Department",
                                               JOptionPane.QUESTION_MESSAGE); 
        }
    
        public void getId()
        {
            stringid = JOptionPane.showInputDialog(null,"Enter Course ID","Enter Course ID",
                                                   JOptionPane.QUESTION_MESSAGE); 
            id = Integer.parseInt(stringid);
        }
    
        public void getCredits()
        {
            stringcredits = JOptionPane.showInputDialog(null,"Enter Credits","Enter Credits",
                                                        JOptionPane.QUESTION_MESSAGE); 
            credits = Integer.parseInt(stringcredits);
        }
    
        public void getLettergrade()
        {
            letter_grade = JOptionPane.showInputDialog(null,"Enter Letter Grade",
                                                       "Enter Letter Grade",
                                                       JOptionPane.QUESTION_MESSAGE); 
        }
    
        public void getQP()
        {
            // The "==" operator is not so useful for testing Strings.
            // Use the "equals" method for testing String equality.
            // "toUpperCase" is another option: not necessary.
            if(letter_grade.toUpperCase().equals("A"))
                QP=4*credits;
            if(letter_grade=="B")
                QP=3*credits;
            if(letter_grade=="C")
                QP=2*credits;
            if(letter_grade=="D")
                QP=credits;
            if(letter_grade=="F")
                QP=0;
        }
    
        public String toString()
        {
            return "Dept:" + dept + " id:" + id +
                   " credits:" + credits + " grade:" + letter_grade +
                   " QP:" + QP;              
        }
    }

  3. #3
    unhurt is offline Member
    Join Date
    Oct 2007
    Posts
    21
    Rep Power
    0

    Default

    hi, can u explain a little bit more about generics and non generics? what does it means? does it mean i have declare the vector for what im going to use it for?

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    does it mean i have declare the vector for what im going to use it for?
    Yes, that's the general idea. It's an attempt to guarantee type safety at compile time.
    You can choose to not use it but will get "Xlint:unchecked" compiler warnings.
    See Lesson: Generics for more.

  5. #5
    cbrown08 is offline Member
    Join Date
    Oct 2007
    Posts
    4
    Rep Power
    0

    Default one final snag

    Thanks for the help so far. We've encountered one final snag in the program. When dealing with students with more than one course we need to compute the total quality points and then the gpa(quality points/credits) for each student. So we need the gpa for each student and then the print sorted by gpa from high to low. I've been working on this for the past several days even after your initial help and would really appreciate any additional help. Thanks so much man :D

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.util.Vector;
    import javax.swing.*;
    
    public class GradebookRx extends JFrame 
    {
        private JButton add;
        private JButton print;
        private JButton exit;
        float[] gpa_array=new float[5];
        private int num_students=0;
        Student[] stu=new Student[5];
        JTextArea textArea = new JTextArea();
     
        public GradebookRx()
        {
            super("Student/Course GUI");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            for(int a=0;a<5;a++)
                stu[a]=new Student();
            // Initialize buttons
            ButtonHandler handler = new ButtonHandler();
            JPanel north = new JPanel();
            add = new JButton("Add Student");
            add.addActionListener(handler);
            north.add(add);
            print = new JButton("Print");
            print.addActionListener(handler);
            north.add(print);
            exit = new JButton("Exit");
            exit.addActionListener(handler);
            north.add(exit);
            Container cat = getContentPane();
            cat.add(north, BorderLayout.NORTH);
            cat.add(new JScrollPane(textArea));
            setSize(800,600);
            setLocation(100,100);
            setVisible(true);
    //        test();
        }
    
        /** To test our alogrithms without tedious data entry. */
        private void test()
        {
            add.setEnabled(false);
            stu[0] = new Student("Mickey Mouse", 25, 3);
            stu[0].addCourse(new Course("EE", 123, 3, "B"));
            stu[0].addCourse(new Course("HE", 22, 4, "A"));
            stu[0].addCourse(new Course("CE", 44, 5, "C"));
            
            stu[1] = new Student("Donald Duck", 22, 2);
            stu[1].addCourse(new Course("PE", 99, 2, "C"));
            stu[1].addCourse(new Course("FP", 15, 3, "A"));
    
            stu[2] = new Student("Elmer Fudd", 44, 2);
            stu[2].addCourse(new Course("PH", 101, 4, "A"));
            stu[2].addCourse(new Course("ES", 220, 5, "A"));
        }
    
        public class ButtonHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                JButton button = (JButton)e.getSource();
                if(button == add)
                {
                    num_students++;
                    stu[num_students].getData();
                }
                else if(button == print)
                {
                    System.out.println("Printing all courses and students");
                    printAllData();
                } else if(button == exit)
                    System.exit(0);
            }
        }
    
        private void printAllData()
        {
            textArea.setText("");
            Student[] sorted = sortByGPA();
            for(int j = 0; j < sorted.length; j++)
            {
                textArea.append("\n");
                textArea.append(sorted[j] + "\n");
                printCourseData(sorted[j].getVector());
                textArea.append("------------");
            }
        }
    
        private Student[] sortByGPA()
        {
            Student[] sorted = getCopy();
            // Sort and return this copy of non-null elements.
            for(int j = 0; j < sorted.length; j++)
            {
                float max = sorted[j].getGPA();
                int maxIndex = j;
                for(int k = j+1; k < sorted.length; k++)
                {
                    if(sorted[k].getGPA() > max)
                    {
                        max = sorted[k].getGPA();
                        maxIndex = k;
                    }
                }
                if(maxIndex != j)
                {
                    // found higher gpa: swap elements
                    Student temp = sorted[j];
                    sorted[j] = sorted[maxIndex];
                    sorted[maxIndex] = temp;
                }
            }
            return sorted;
        }
    
        private Student[] getCopy()
        {
            // count number of non-null elements
            int count = 0;
            for(int j = 0; j < stu.length; j++)
            {
                if(stu[j].getName() == null)
                    break;
                count++;
            }
            Student[] temp = new Student[count];
            System.arraycopy(stu, 0, temp, 0, count);
            return temp;
        }
    
        private void printCourseData(Vector<Course> v)
        {
            for(int j = 0; j < v.size(); j++)
            {
                Course course = v.get(j);
                textArea.append(course + "\n");
            }
        }
     
        public static void main(String[] args)
        {
            new GradebookRx();
        }
    }
    
    class Student
    {
        String name;
        private String stringage;
        private int age;
        private float gpa;
        private int num_courses;
        private String stringnum_courses;
        private int totalqp;
        private Vector<Course> v = new Vector<Course>();
        NumberFormat nf;
    
        public Student()
        {
            this(null, 0, 0);
        }
    
        public Student(String name, int age, int numCourses)
        {
            this.name = name;
            this.age = age;
            this.num_courses = numCourses;
            nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            nf.setMinimumFractionDigits(1);
            updateGPA();
        }
     
        public void getData()
        {
            name = JOptionPane.showInputDialog(null,"Enter Student's Name",
                                               "Enter Student's Name",
                                               JOptionPane.QUESTION_MESSAGE);
            stringage = JOptionPane.showInputDialog(null,"Enter Student's Age",
                                                    "Enter Student's Age",
                                                    JOptionPane.QUESTION_MESSAGE);
            age = Integer.parseInt(stringage);
            stringnum_courses = JOptionPane.showInputDialog(null,"Enter Number of Courses",
                                                            "Enter Number of Courses",
                                                            JOptionPane.QUESTION_MESSAGE);
            num_courses = Integer.parseInt(stringnum_courses);    
            for(int a=0;a<num_courses;a++)
            {
                Course cr = new Course();
                addCourse(cr);
            }
        }
    
        public void addCourse(Course course)
        {
            v.add(course);
            updateGPA();
        }
    
        private void updateGPA()
        {
            int totalQualityPoints = 0;
            int totalCredits = 0;
            for(int j = 0; j < v.size(); j++)
            {
                Course c = v.get(j);
                totalQualityPoints += c.getQP();
                totalCredits += c.getCredits();
            }
            gpa = (float)totalQualityPoints/totalCredits;
        }
    
        public String toString()
        {
            return "Name:" + name + " age:" + age +
                   " num_courses:" + num_courses +
                   " gpa:" + nf.format(gpa);
        }
    
        public String getName()
        {
            return name;
        }
    
        public float getGPA()
        {
            return gpa;
        }
    
        public Vector<Course> getVector()
        {
            return v;
        }
    }
    
    class Course
    {
        // instance variables - replace the example below with your own
        private int id;
        private String dept;
        private int credits;
        private String letter_grade;
        private String stringid;
        private String stringcredits;
        private int QP;
    
        public Course()
        {
            getInput();
            calculateQP();
        }
    
        public Course(String dept, int id, int credits, String grade)
        {
            this.dept = dept;
            this.id = id;
            this.credits = credits;
            this.letter_grade = grade;
            calculateQP();
        }
     
        public void getInput()
        {
            dept = JOptionPane.showInputDialog(null,"Enter Department","Enter Department",
                                               JOptionPane.QUESTION_MESSAGE); 
            stringid = JOptionPane.showInputDialog(null,"Enter Course ID","Enter Course ID",
                                                   JOptionPane.QUESTION_MESSAGE); 
            id = Integer.parseInt(stringid);
            stringcredits = JOptionPane.showInputDialog(null,"Enter Credits","Enter Credits",
                                                        JOptionPane.QUESTION_MESSAGE); 
            credits = Integer.parseInt(stringcredits);
            letter_grade = JOptionPane.showInputDialog(null,"Enter Letter Grade",
                                                       "Enter Letter Grade",
                                                       JOptionPane.QUESTION_MESSAGE); 
        }
    
        private void calculateQP()
        {
            if(letter_grade.toUpperCase().equals("A"))
                QP=4*credits;
            if(letter_grade.toUpperCase().equals("B"))
                QP=3*credits;
            if(letter_grade.toUpperCase().equals("C"))
                QP=2*credits;
            if(letter_grade.toUpperCase().equals("D"))
                QP=credits;
            if(letter_grade.toUpperCase().equals("F"))
                QP=0;
        }
    
        public int getQP()
        {
            return QP;
        }
    
        public int getCredits()
        {
            return credits;
        }
    
        public String toString()
        {
            return "Dept:" + dept + " id:" + id +
                   " credits:" + credits + " grade:" + letter_grade +
                   " QP:" + QP;              
        }
    }
    Last edited by hardwired; 11-05-2007 at 08:03 AM. Reason: added "this(null,0,0);" to Student no-arg constructor

  7. #7
    bair is offline Member
    Join Date
    Nov 2007
    Posts
    1
    Rep Power
    0

    Default

    Nothing prints when I use that new code, just a blank screen when I hit print after inputting data.

  8. #8
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    public class ButtonHandler implements ActionListener
    {
        ...
            if(button == add)
            {
                // Problem was here: incrementing num_students too early
                // which skips over the array element at index = 0.
    //            num_students++;
                stu[num_students].getData();
                num_students++;
            }
    So the first element in the stu array (at index = 0) was skipped and you were
    initializing the second element (index = 1). This caused trouble in the loop
    of the getCopy method:
    Java Code:
    for(int j = 0; j < stu.length; j++)
    {
        if(stu[j].getName() == null)
            break;
        count++;
    }
    which broke out at the first element (j = 0) because it had been skipped.
    So getCopy returned a zero-length array to the sortByGPA method.

    In conjunction with this you could alter the test method to be able
    to add more elements to the array:
    Java Code:
    private void test()
    {
        // remove the add.setEnabled line
        ...
        stu[2].addCourse(new Course("ES", 220, 5, "A"));
        num_students = 3;
    }

Similar Threads

  1. Vectors of Vectors or hash-somethings?
    By mindwarp in forum New To Java
    Replies: 3
    Last Post: 03-10-2008, 03:57 PM
  2. Help with Vectors and Strings...
    By kaban in forum New To Java
    Replies: 2
    Last Post: 12-09-2007, 10:04 AM
  3. Can't access two vectors independantly?
    By splinter64uk in forum New To Java
    Replies: 2
    Last Post: 11-29-2007, 12:57 AM
  4. Vectors vs ArrayList
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-28-2007, 11:29 AM

Posting Permissions

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