Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Linux Archive
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 10-31-2007, 07:07 AM
Member
 
Join Date: Oct 2007
Posts: 4
cbrown08 is on a distinguished road
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.

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 10:59 AM.
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 10-31-2007, 11:59 AM
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
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.
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; } }
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 11-01-2007, 09:17 PM
Member
 
Join Date: Oct 2007
Posts: 21
unhurt is on a distinguished road
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?
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 11-01-2007, 10:01 PM
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 11-05-2007, 02:51 AM
Member
 
Join Date: Oct 2007
Posts: 4
cbrown08 is on a distinguished road
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
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 11-05-2007, 08:51 AM
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
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 09:03 AM. Reason: added "this(null,0,0);" to Student no-arg constructor
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 11-05-2007, 06:15 PM
Member
 
Join Date: Nov 2007
Posts: 1
bair is on a distinguished road
Nothing prints when I use that new code, just a blank screen when I hit print after inputting data.
Bookmark Post in Technorati
Reply With Quote
  #8 (permalink)  
Old 11-05-2007, 08:56 PM
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
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:
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:
Code:
private void test() { // remove the add.setEnabled line ... stu[2].addCourse(new Course("ES", 220, 5, "A")); num_students = 3; }
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Vectors of Vectors or hash-somethings? mindwarp New To Java 3 03-10-2008 04:57 PM
Help with Vectors and Strings... kaban New To Java 2 12-09-2007 11:04 AM
Can't access two vectors independantly? splinter64uk New To Java 2 11-29-2007 01:57 AM
Vectors vs ArrayList Java Tip Java Tips 0 11-28-2007 12:29 PM
Using Vectors in Java JavaForums Java Blogs 0 11-04-2007 09:31 PM


All times are GMT +3. The time now is 12:07 AM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org