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

Thread: instantiating class objects from an array

  1. #1
    Junior Member
    Join Date
    Apr 2011
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question instantiating class objects from an array

    I need to instantiate a new class object from an array that I have created from user input in a JFrame. I can save the data to an array of objects but I can't create the class object with my new array. I need to create 7 class objects and perform sorts based on name, gpa, grade 1, grade 2, and grade 3. I can do the sorting no problem when I create an array like this:

    Student studentsArray[] = {new Student("Andrey", "Hrismok", 4.0, 'A', 'A', 'A'),
                new Student("Jonathan", "Stormer", 3.76, 'B', 'A', 'A'),
                new Student("Monica", "Fitshweb", 4, 'A', 'A', 'A'),
                new Student("Wenemal", "Stormer", 2.81, 'C', 'B', 'A'),
                new Student("Kissadil", "Levy", 3.76, 'A', 'A', 'B'),
                new Student("Cartans", "Buweno", 3.0, 'C', 'B', 'A'),
                new Student("Craig", "Wibrele", 3.97, 'A', 'A', 'A')};

    but when I try to create an array for each student and then create a Student object from the array suddenly netbeans thinks I am making a call to a method and not a constructor in the student class.

    Code:
     public void getStudentData(){
            studentRecord[0] = jtfFirstName.getText();
            studentRecord[1] = jtfLastName.getText();
            studentRecord[2] = calcGPA();
            studentRecord[3] = jtfGrade1.getText();
            studentRecord[4] = jtfGrade2.getText();
            studentRecord[5] = jtfGrade3.getText();
     
            for (int i = 0; i < 6; i++){
            System.out.print(studentRecord[i] + " ");
            }
            Student tempStudent = new Student (studentRecord[0], studentRecord[1],
                    studentRecord[2], studentRecord[3], studentRecord[4],
                    studentRecord[5]);

    Here is all of my pertinent code for reference:

    Student.java
    class Student extends Person {
     
        // Defining the instance variables. They all have the default modifier.
        private Name name;
        private String university, school, study;
        private double gpa;
        private char grade1, grade2, grade3;
     
        // Default constructor.
        private Student() {
        }
     
        //Constructor for Project 4
        public Student(String firstName, String lastName, double gpa, char grade1,
                char grade2, char grade3) {
            name = new Name(firstName, lastName);
            this.gpa = gpa;
            this.grade1 = grade1;
            this.grade2 = grade2;
            this.grade3 = grade3;
     
        }
     
        public double getGpa() {
            return gpa;
        }
     
        public char getGrade1() {
            return grade1;
        }
     
        public char getGrade2() {
            return grade2;
        }
     
        public char getGrade3() {
            return grade3;
        }
    ...

    Name.java
    package P4;
     
    public class Name implements Comparable<Name> {
     
        private String firstName, lastName;
     
        public Name(String firstName, String lastName) {
            if (firstName == null || lastName == null) {
                throw new NullPointerException();
            }
            this.firstName = firstName;
            this.lastName = lastName;
        }
     
        public String toString() {
            return lastName + ", " + firstName;
        }
     
        public int compareTo(Name name) {
            int comp = lastName.compareTo(name.lastName);
            return (comp != 0 ? comp : firstName.compareTo(name.firstName));
        }
    }

    GradeFrame.java
    package P4;
     
    //GradeFrame.java
    //Our many imports :)
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import javax.swing.JOptionPane.*;
     
    //GradeFrame class
    public class GradeFrame extends JFrame {
     
        //Declare class variables
        double gpa;
        Object studentRecord[] = new Object[6];
        int grades[] = {0, 0, 0};
        JTextField jtfGPA = new JTextField(13);
        JTextField jtfFirstName = new JTextField(20);
        JTextField jtfLastName = new JTextField(20);
        JTextField jtfGrade1 = new JTextField(3);
        JTextField jtfGrade2 = new JTextField(3);
        JTextField jtfGrade3 = new JTextField(3);
        JButton jbtComputeGPA, jbtNextStudent, jbtFinished;
     
        public void gradeFrame() {
     
            //creates new JFrame object
            JFrame frame = new GradeFrame();
            frame.setTitle("Student's Grades and GPA");
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(1, 1);
            frame.pack();
            frame.setVisible(true);
        }
     
        //GradeFrame Constructor adds GUI components.
        public GradeFrame() {
     
            //Create a Compute GPA Button
            jbtComputeGPA = new JButton("Compute GPA");
            jbtNextStudent = new JButton("Next Student");
            jbtFinished = new JButton("Finished");
     
            //add elements to GUI
            setLayout(new GridLayout(7, 2));
            add(new JLabel("First Name:"));
            add(jtfFirstName);
            add(new JLabel("Last Name:"));
            add(jtfLastName);
            add(new JLabel("Grade 1: (0 - 100)"));
            add(jtfGrade1);
            add(new JLabel("Grade 2: (0 - 100)"));
            add(jtfGrade2);
            add(new JLabel("Grade 3: (0 - 100)"));
            add(jtfGrade3);
            add(jbtComputeGPA);
            add(jtfGPA);
            add(jbtNextStudent);
            add(jbtFinished);
     
            //create Compute GPA button action listener
            jbtComputeGPA.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) {
     
                    getGrades();
                    jtfGPA.setText("GPA: " + calcGPA());
                }
            });
     
            //create Next Student button action listener
            jbtNextStudent.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    getStudentData();
                }
            });
        }
     
        public void getStudentData(){
            //String[] tempStudent = new String[6];
            studentRecord[0] = jtfFirstName.getText();
            studentRecord[1] = jtfLastName.getText();
            studentRecord[2] = calcGPA();
            studentRecord[3] = jtfGrade1.getText();
            studentRecord[4] = jtfGrade2.getText();
            studentRecord[5] = jtfGrade3.getText();
     
            for (int i = 0; i < 6; i++){
            System.out.print(studentRecord[i] + " ");
            }
            Student tempStudent[] = new Student (studentRecord[0], studentRecord[1],
                    studentRecord[2], studentRecord[3], studentRecord[4],
                    studentRecord[5]);
            Student student1 = new Student("Alice", "King", 3.67, 'A', 'B', 'C');
        }
     
        public void getGrades() {
     
            try {
                //add grade values which correspond to index value.
                int grade1 = Integer.parseInt(jtfGrade1.getText());
                gradeTest(grade1);
                int grade2 = Integer.parseInt(jtfGrade2.getText());
                gradeTest(grade2);
                int grade3 = Integer.parseInt(jtfGrade3.getText());
                gradeTest(grade3);
                grades[0] = grade1;
                grades[1] = grade2;
                grades[2] = grade3;
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "Values entered for grades must be "
                        + "from 0 - 100\n\nActual error msg: " + ex,
                        "Try Again.",
                        JOptionPane.ERROR_MESSAGE);
            } catch (RangeException ex) {
                JOptionPane.showMessageDialog(jbtComputeGPA, ex, "Values entered for"
                        + " grades must be from 0 - 100.",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
     
        public void gradeTest(int grade) throws RangeException {
            if (grade < 0 || grade > 100) {
                throw new RangeException("0 - 100");
     
            }
     
        }
     
        public double calcGPA() {
     
            int sum = 0;
            for (int i = 0; i < 3; i++) {
                if (grades[i] >= 90) {
                    sum += 4;
                } else if (grades[i] >= 80) {
                    sum += 3;
                } else if (grades[i] >= 70) {
                    sum += 2;
                } else if (grades[i] >= 60) {
                    sum += 1;
                } else {
                    sum += 0;
                }
            }
            double gpa = ((int) ((sum / 3.0) * 100) / 100.0);
     
            return gpa;
     
     
     
        }
    }

    My sort classes are in a different package, except "Name" because I am trying to build off a working example that doesn't use a GUI to import data from the user. Anyway, I know my code is a mess at this point. Thanks for any help!


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: instantiating class objects from an array

    The code you posted above is different in at least one case: GoodFrame.java
     Student tempStudent[] = new Student (studentRecord[0], studentRecord[1],
                    studentRecord[2], studentRecord[3], studentRecord[4],
                    studentRecord[5]);

    tempStudent is defined as an array, so it must be treated as such. I can't guarantee this is the problem as there are 2 different versions of the same code - if this is not the problem I recommend posting the complete error code the compiler is given you

  3. The Following User Says Thank You to copeg For This Useful Post:

    BadAnti (April 12th, 2011)

  4. #3
    Junior Member
    Join Date
    Apr 2011
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: instantiating class objects from an array

    cannot find symbol
    symbol : constructor Student(java.lang.Object,java.lang.Object,java.lan g.Object,java.lang.Object,java.lang.Object,java.la ng.Object)
    location: class P4.Student
    Student tempStudent[] = new Student (studentRecord[0], studentRecord[1],
    1 error

    in regards to this line in GradeFrame.java:
    Student tempStudent[] = new [U][I]Student[/I][/U] (studentRecord[0], studentRecord[1],

    Sorry about the confusion in the different versions of code. I am trying different things as I am posting. At this point I am probably doing more harm than good to my code but I have to keep trying

    ============ EDIT=============

    Ok noticed my array was of objects and I am trying to pass objects as arguments(?) to my constructor which is looking for String, String, double, char, char, char. So how do I save my user input as String, String, double, char, char, char? Part of the assignment is saving it as an array. As far as I know arrays can only contain one type of variable. *pulls hair out* Thanks for your help btw.
    Last edited by BadAnti; April 12th, 2011 at 03:13 PM. Reason: noticed I had an array of objects.

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: instantiating class objects from an array

    So how do I save my user input as String, String, double, char, char, char?
    You could cast the Object to the specified type.
    Object val1 = "test";
    String val2 = (String)val;
    Its probably not the best practice, but if you must keep them in an array this would be one way to go about it.

  6. The Following User Says Thank You to copeg For This Useful Post:

    BadAnti (April 12th, 2011)

Similar Threads

  1. How to store objects from a class inn an array?
    By dironic88 in forum Object Oriented Programming
    Replies: 1
    Last Post: April 7th, 2011, 02:42 PM
  2. Need help with instantiating a class
    By suxen in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 30th, 2011, 03:35 PM
  3. [SOLVED] Array of objects, invoking constructor for one changes others
    By BigFoot13 in forum Object Oriented Programming
    Replies: 4
    Last Post: October 24th, 2010, 01:30 PM
  4. FAQ: find variable in an array of objects
    By dalek in forum Object Oriented Programming
    Replies: 1
    Last Post: April 5th, 2010, 12:40 PM
  5. [SOLVED] Creation of objects of Array in Java
    By sadi_shihab in forum Collections and Generics
    Replies: 4
    Last Post: July 9th, 2009, 01:38 PM