1 Replies - 864 Views - Last Post: 05 May 2013 - 01:45 PM Rate Topic: -----

#1 yyad  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-May 13

Java basic grade book

Posted 05 May 2013 - 01:40 PM

Hello all,

I was working on this program where I am supposed to create a basic grade book. The program gets student name and grade from gui and displays on GUI. I was trying to connect this program with database and I was successful doing so. However , the problem I cam across was I CANNOT access the users input i.e. student name and grade which is stored in the list in my database or in console. I tried defining many methods to get those inputs but I failed. Any help would be greatly appreciated.



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// creating a frame within the class guiApp
public class GuiApp extends JFrame {
 StudentList list = new StudentList();
    class StudentPanel extends JPanel{
 // getting all the component necessary to print the output of the program   
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setFont(
                    new Font("Nanum Gothic",Font.BOLD,32));
            //g.drawString("This is a test", 50,50);
            g.setColor(new Color(100,0,255));
            g.drawString("Names",20,70);
             g.drawString("Grades",240,70);
             
             //list.getHighest();
            //g.fillRect(100,10,200,200);
             
          for (int i=0;i<list.length();i++){
                Student tmp = list.get(i);

                g.drawString(tmp.name,20,120+i*60);
                FontMetrics fm = g.getFontMetrics();
                String s= String.format("%d",tmp.grade);
                int w = fm.stringWidth(s);
                g.drawString(tmp.grade+"",350-w,120+i*60);
                g.drawString("The Highest grade is : "+list.getHighest()+"",list.length(),120+list.length()*60);
                g.drawString("The Lowest  grade is : "+list.getLowest ()+"",list.length(),170+list.length()*60);
                g.drawString("The Average grade is : "+list.getAverage()+"",list.length(),210+list.length()*60);

     }
       }
    
    }
  
    
    // calling the methods created in studentlist 
public void actionPerformed(ActionEvent e){
             list.getHighest();
             list.getLowest();
             list.getAverage();
             repaint();
     }


       
public GuiApp(){
    // super("GuiApp");
     
     // Menus
     
     JMenuBar jmb = new JMenuBar();
     
     setJMenuBar(jmb);
     JMenu jm =  jmb.add(new JMenu("File"));
     jm.setMnemonic('F');
     // creating items under file menu
     JMenuItem jmi = jm.add(
             new JMenuItem("New...",'N'));
     // making new item ask user for inputs
     jmi.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e){
             String s = JOptionPane.showInputDialog("Enter 1 or more student names with grades");
             if(s!=null){
                // caling method from studentlist to put user input in it
             list.getData(s);
       
             repaint();
             }
         }
     });
     // creatig and item for user to add further inputs
     jmi = jm.add(
             new JMenuItem("Add...",'A'));
     jmi.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e){
              String s = JOptionPane.showInputDialog("Enter 1 or modre student names with grades");
              if(s!=null){
              list.getAdddata(s);
              repaint();
             }
         }
     });
     // adding separator to specify the item is for exiting the program
     jm.addSeparator();
     jmi= jm.add(
             new JMenuItem("Exit",'X'));
     
     jmi.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e){
             System.exit(0);
         }
     });
     // taking the user inputs and sorting it
     jm =  jmb.add(new JMenu("Sort"));
     jm.setMnemonic('S');
     // sorting the grade by name
     jmi = jm.add(
             new JMenuItem("Name",'N'));
     jmi.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e){
             //calling method from studentlist to perform the sorting
             list.sortByName();
             repaint();
             
         }
     });
     
     //sorting by grade in descending order
     jmi = jm.add(
             new JMenuItem("Grade",'G'));
     
     jmi.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e){
             // calling method to perform the task from studentlist 
             list.sortByGrade();
             repaint();
         }
     });
     
     // creating the helo item within menu 
     jm =  jmb.add(new JMenu("Help"));
     jm.setMnemonic('H');
     // this provides a brief introduction about the program
     jmi = jm.add(
             new JMenuItem("About",'A'));
     
     jmi.addActionListener(new ActionListener(){
         
         @Override
         public void actionPerformed(ActionEvent e){
             
            JOptionPane.showMessageDialog(GuiApp.this,
                                              new JLabel("<html><big><Centre>"
                    + "Gui Program v1.0 <br>"
                    +"Copyright\u00a9 2012 Yogesh Yadav <br>"
                    +"All Rights reserved."
                    + "</big></html>"
                    +"</centre></big></html>"),
            
                                              
             "About",JOptionPane.INFORMATION_MESSAGE);
         }
     });
     
     // calling the class created above
     
     add(new StudentPanel());
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setBounds(100,100,400,300);
     setVisible(true);
     
 }
public static void main(String[] args) {
   new GuiApp();
  
  
        
       
       
    
     
  }
}




This is second class for creating student list


import java.util.StringTokenizer;

// creating class
class Student{
    
    // for two parameter as name and grade
    String name;
    int grade;
public Student(String name, int g){
    this.name= name;
    this.grade=g;
   }
public Student(){
    this("",0);
}
public String getName(){
    return this.name;
}
public int getGrade(){
    return this.grade;
}

}
// creating the list of students and getting input 
public class StudentList {
Student[] students;
public StudentList(){
  students= new Student[0];
    }
    // processing user input and separating the name with grades
    public void getData(String input){
    StringTokenizer st = new StringTokenizer(input);
    
    students= new Student[st.countTokens()/2];
    
    for(int i =0;st.hasMoreTokens();i++){
        String name = st.nextToken();
        int grade= Integer.parseInt(st.nextToken());
        students[i]= new Student(name,grade);
        
    }
 }
 public void getAdddata(String input){
   StringTokenizer st = new StringTokenizer(input);
   Student[]oldlist = students;
   students= new Student[oldlist.length+st.countTokens()/2];
   for(int i= 0;i<oldlist.length;i++)
       students[i]=oldlist[i];
   for(int i=oldlist.length;st.hasMoreTokens();i++){
        String name = st.nextToken();
        int grade= Integer.parseInt(st.nextToken());
        students[i]= new Student(name,grade);
       
   }
    
     
     
 }
 

   // creating method to sort the names provided by the user alphabetically
    
 public void sortByName(){
     for(int i = 0;i <length()-1;i++)
         for(int j=0;j<length()-1;j++)
         if(students[j+1].name.compareTo(students[j].name)<0){
             
             Student tmp = students[j];
             students[j]= students[j+1];
             students[j+1]= tmp;
 }
 }
 
 
     
// creating method to sort grades in descending order
 public void sortByGrade(){
   // loop to go through every element in array
    for(int i =0;i<length()-1;i++){
        int largest =i;
        for(int j= largest+1;j<length();j++)
            if(students[j].grade>students[largest].grade)
                largest=j;
        {
       // supoose the first elememt to be the largest and comaring with the next 
         Student tmp= students[i];
        students[i]= students[largest];
        students[largest]=tmp;
    }
 }  
}
 

 
 
  
 public  int getHighest(){
    // assuming the first grade to be the minimum and then comparing
    int hi=Integer.MIN_VALUE;
    // going through loop to compare value
    for(int i=0;i<length();i++)
        // comparing every grade for hoghest value
        if(students[i].grade >hi) hi=students[i].grade;
    return hi;
    }
 
 public int getLowest(){
   int lo = Integer.MAX_VALUE;
    for(int i=0;i<length();i++)
        if(students[i].grade <lo) lo=students[i].grade ;
    return lo;
    
    
}
public float getAverage(){
    // assuming the total grade to be zero
    float total=0;
    // creating loop to go through each and every grade in array
    for (int i=0;i<length();i++)
        total+=students[i].grade;
    return total/students.length;
}
     
public int length(){
      return students.length;
  }
  public Student get(int n){
      return students[n];
      
  }
  

    }







This is the code for database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class GuiDatabase {
    
    
    // JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
static final String DB_URL = "jdbc:mysql://localhost/JAVA"; // Database credentials
static final String USER = "root";
static final String PASS = "yogesh12";


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException {
       
        // NEED TO GET STUDENT NAME AND GRADE FROM STUDENTLIST CLASS OR GUI CLASS
        
        try{
    
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Connecting to database...");
    DriverManager.getConnection(DB_URL,USER,PASS);

}
catch(Exception e){
    System.out.println(e);
}
       Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
       Statement stmt = conn.createStatement();
       
    
       stmt.execute("INSERT INTO Gradebook values('"+name+"')");
}
}   



Is This A Good Question/Topic? 0
  • +

Replies To: Java basic grade book

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10438
  • View blog
  • Posts: 38,651
  • Joined: 27-December 08

Re: Java basic grade book

Posted 05 May 2013 - 01:45 PM

A few things. First, and most importantly, adopt an indentation convention. It's very hard to follow your code. Second, your Main class should only have a few lines of code to start the program. You really should look into software architecture and design. The MVC pattern is very applicable here. The goal is to separate the UI from the program state/data. Lastly, StringTokenizer should be avoided in favor of the String split() method, as StringTokenizer is legacy code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1