New Posts  All Forums:Forum Nav:

Java Assistance.

post #1 of 9
Thread Starter 
I've written a program for class in which a user enters their first name, last name, GPA, and GMAT scores into an interface. The program then calculates whether or not to accept the student go graduate school based on certain criteria. I am then able to store that info into a database.

The problem I am facing is in my insert loop. It not only adds the current student info, but also the info again from each of the previous users entered while in the same session. I only want the current user and not the previous users again.

Code:
package Project2;


import java.sql.*;
import java.io.*;
import javax.swing.*;
import java.util.*;

public class StudentInsert extends java.lang.Object
{
    private String url = "jdbc:odbc:Student2;";
    private Connection myConnect;
    private Vector vec;
    private Iterator itVec;
    private static final int CAP = 20;
    private static final int AddCAP = 10;
    
    public StudentInsert()
    {
        this(null);
    }
    
    public StudentInsert(Vector inVec)
    {
        vec = new Vector(CAP,AddCAP);
        vec = inVec;
        itVec = vec.iterator();
        
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            myConnect = DriverManager.getConnection(url);
        }
        catch(ClassNotFoundException cnf)
        {
            JOptionPane.showMessageDialog(null,"Failed to load jdbc/odbc driver.");
            cnf.printStackTrace();
            System.exit(1);
        }
        catch(SQLException sql)
        {
            JOptionPane.showMessageDialog(null,"Unable to Connect");
            sql.printStackTrace();
        }
        
        insertData();
    }
    public void insertData()
    {
        Statement myState;
        int res;
        String query = new String();
        
        try
        {
            myState = myConnect.createStatement();

            while(itVec.hasNext())
            {
                MISStudent temp = new MISStudent();
                temp = (MISStudent)itVec.next();
                query = "INSERT INTO MISStudent2("+"LastName,FirstName,GPA,GMAT,Admitted)"+"VALUES("+
                        "'" + temp.getLName() + "', " +
                      "'" + temp.getFName() + "', " +
                      "'" + String.valueOf(temp.getGpa()) + "', " +
                      "'" + String.valueOf(temp.getGmat()) + "', " +
                      "'" + String.valueOf(temp.getAdmitted()) + "'" + ")"; 
                res = myState.executeUpdate(query);
                if(res==1)
                {
                    JOptionPane.showMessageDialog(null,"Data insertion succeeded for "+temp.getFName() +" "+temp.getLName());
                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Data insertion failed for"+temp.getFName() +" "+temp.getLName());
                }
            }
            myState.close();
        }
        catch(SQLException sql)
        {
            JOptionPane.showMessageDialog(null,"Unable to Connect");
            sql.printStackTrace();
        }
    }
}
Any help would be most appreciated.
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
post #2 of 9
Code:
    public StudentInsert(Vector inVec)
    {
        vec = new Vector(CAP,AddCAP);
        vec = inVec;
        itVec = vec.iterator();
....
It's odd that you create a vector with a specific size, then dump it, replacing it with the copy that was passed in to the constructor. Regardless, I can't see anything here that would cause duplicate data entry. I think you need to take a look at what creates an instance of the StudentInsert class, and what you're passing into the constructor. Careful that you're only creating one InsertData instance, and that you empty the vector before you add new students to it. Note that inVec is a referenced vector. By that, I mean, if it is modified outside the class, it will be modified inside StudentInsert as well, since it's just a reference to a single instance.

Debug statements can go a long way here. At the top of the constructor, System.out.println the size of the vector. If that number keeps getting larger with each add, that should prove to you that the problem is not inside InsertData.

Code:
    public void insertData()
This is dangerous. Change this to private, to ensure it is called locally and once only. If you call it a second time, the iterator will still be at end of the iteration, since vec.iterator() only gets called in the constructor. If you try to modify the original vector that was passed into the constructor, and then call insertData, I imagine you'd get a concurrent modification exception or something like that.

Also, you can save on some catch statements by moving the call of this function to inside the try block:

Code:
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            myConnect = DriverManager.getConnection(url);
            insertData();
        }
-- and then declare insertData() as throws SQLException. Now you can junk the catch block and the try clause in insertData.

Good luck!
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
post #3 of 9
Thread Starter 
Thanks for the great tips, although I modified the code, but my message box still tells me each person I have entered data for in a current session. For example, if I add one person to the database I will get one message box. If I exit and go back into the program same thing which is perfect.

The problem I'm facing is when I add concurrent data I'll get a message box for each person I enter. For example, if I enter Steve and then Joey my message box pops up twice showing me I entered not only Steve, but also Joey thereafter.

I think it may be a problem with my insert data method.
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
post #4 of 9
You've got to empty that vector before adding the new MISStudent instances to it and passing it to the StudentInsert constructor. Instead, you're adding new MISStudent instances to the vector and passing that continually growing vector as-is. It's hard to be more specific without seeing the code that instantiates the StudentInsert object.
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
post #5 of 9
Thread Starter 
Quote:
Originally Posted by Scriptorum View Post
It's hard to be more specific without seeing the code that instantiates the StudentInsert object.
Code:
    private ArrayList list;
    private Iterator itList;
    private Vector insertVec;
    private StuGetData stdb;   
    private MISStudent e;
    
        public void checkAdmission()
        {
            double gpa, gmat;
            String fn = new String();
            String ln = new String();
            
            e = new MISStudent();

            try
            {
            fn = firstNameJTextField.getText();
            e.setFName(fn);
            }
            catch (NameException nE)
            {   
                jTextArea1.setText(nE.toString());
                return;
            }
            try
            {
            ln = lastNameJTextField.getText();
            e.setLName(ln);

            }
            catch (NameException nE)
            {
                jTextArea1.append(nE.toString());
                 return;
            }
            try
            {
            gpa = Double.parseDouble(gpaJTextField.getText());
            e.setGpa(gpa);
            }
            catch (GPAException gpaE)
            { 
                jTextArea1.append(gpaE.toString());
                return;
            }
            catch(NumberFormatException nfe)
            {
              jTextArea1.append(nfe.toString());
              return;   
            }
            try
            {
            gmat = Double.parseDouble(gmatJTextField.getText());
            e.setGmat(gmat);
            }
            catch(GMATException gmatE)
            {
                jTextArea1.append(gmatE.toString());
                return;
            }
            catch(NumberFormatException nfe)
            {
              jTextArea1.append(nfe.toString());
              return;   
            }

            e.setAdmitted(gpa, gmat);

            if (e.getAdmitted())
            {
                statusJTextField.setText("Admitted");
            }
            else
            {
                statusJTextField.setText("Not Admitted");
            }
            }
         private void writeData()
     {
         try
         {
         MISStudent addE = new MISStudent();
         addE = e;
         insertVec.add(addE);
         }
         catch(Exception ex)
         {
             System.out.println("Update Was Not Successful.");
             jTextArea1.append("n Update Was Not Nuccessful."); 
         }
         new StudentInsert(insertVec);
     }
  
    
    public void clearData()
{
lastNameJTextField.setText("");
firstNameJTextField.setText("");
gpaJTextField.setText("");
gmatJTextField.setText("");
statusJTextField.setText("");
calculateButton.setEnabled(true);
                jButtonNext.setEnabled(true);
}
    
     public void clearMessage()
        {
            jTextArea1.setText("");
        }
        
         void  displayData()
        {// displays data from the database to GUI
            MISStudent tem = new MISStudent();
            if (itList.hasNext())
        {
                tem = (MISStudent) itList.next();  //get an element from the array list iterator
                firstNameJTextField.setText(tem.getFName());       
lastNameJTextField.setText(tem.getLName());
gpaJTextField.setText(String.valueOf(tem.getGpa()));
gmatJTextField.setText(String.valueOf(tem.getGmat()));
statusJTextField.setText(String.valueOf(tem.getAdmitted())); 
                calculateButton.setEnabled(true);
                jButtonNext.setEnabled(false);
        }
        else
        {
                firstNameJTextField.setText("No More Data");
lastNameJTextField.setText("No More Data");
gpaJTextField.setText("No More Data");
gmatJTextField.setText("No More Data");
statusJTextField.setText("No More Data"); 
                calculateButton.setEnabled(false);
                jButtonNext.setEnabled(false);
                
        }
    }
}
This the GUI to the program that instantiates everything by action events. Thanks for the assistance.
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
post #6 of 9
Your primary problem is here:

Code:
private Vector insertVec;
You've scoped insertVec as a member variable rather than a local variable. This vector is only to be used for the writeData method, therefore it belongs there:

Code:
private void writeData()
{
    private Vector insertVec;
    try
    {
        MISStudent addE = new MISStudent();
        addE = e;
        insertVec.add(addE);
    }
    catch(Exception ex)
    {
        System.out.println("Update Was Not Successful.");
        jTextArea1.append("n Update Was Not Nuccessful."); 
    }
    new StudentInsert(insertVec);
}
This alone should solve your problem. By scoping insertVec as a member variable, its contents persist between multiple calls to writeData. Therefore, you're continually adding new students to this vector, when what you really want is just to store one. Another solution is to empty insertVec before calling add, but that's just masking the real problem, which is that insertVec is scoped wrong.

Just as classes should hide unnecessary details from other classes, functions should hide unnecessary details from the class itself.
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
post #7 of 9
Thread Starter 
Thanks for help mate.

When I try and compile, the 'Private Vector insertVec' gives an 'illegal start of expression' error. I don't think I'm missing a bracket anywhere?
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
post #8 of 9
Oh, yeah, whoops. Remove the private keyword. That's a modifier that only belongs on member variables. Also you're probably initializing insertVec somewhere else. That initialization needs to be moved to writeData. Such as:

Code:
private void writeData()
{
   Vector insertVec = new Vector();
...
It's been a long time since I've done any serious Java development, but I think Java now supports parameterized types, which means you can do something like this for more type safety:

Code:
   Vector<MISStudent> insertVec = new Vector<MISStudent>();
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
    
CPUGraphicsRAMHard Drive
Intel 2.4 Core i7 AMD Radeon HD 6750M 8 GB 1067 MHz DDR3 750 GB 
OS
Mac OS-X Lion 
  hide details  
Reply
post #9 of 9
Thread Starter 
Works perfect. Thanks again mate.
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
Legendary
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6750 ASUS P5B Deluxe XFX 8600GT 2 x 2GB G.Skill PQ 
Hard DriveOSMonitorKeyboard
Seagate 250GB Windows 7 x64 Samsung 225BW Saitek Eclipse 
PowerCaseMouseMouse Pad
PC P&C Quad 750W Silencer Thermaltake Tsunami Dream Logitech MX518 Func 1030 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming