![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
|
review my code
This is an school asignment I finished. The program reads a file of student info if it exists. The user enters student info. A dialog box apreas if the Student's name already exists in the file/array list. User can then save the new student info or not. There is no need for error checking in this assignment. On existing the ArrayList of stduents is writen to file.
I am looking from some suggestions, commetns, complaints on how to make it better, more effient, more human readable, easier to manage, etc. I have yet to add comments to the enteir program. import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class StudentDatabase extends JFrame
{
// declare the name of the text file that stores the student datatbase
private final File STUDIO_FILE = new File("studio.txt");
// create an IO object for the database file
private StudentIO studio = new StudentIO(STUDIO_FILE);
// declare the GUI text fields
private JTextField nameField = new JTextField(20);
private JTextField addressField = new JTextField(20);
private JTextField cityField = new JTextField(20);
private JTextField stateField = new JTextField(20);
private JTextField majorField = new JTextField(20);
// default Student Database constructor
public StudentDatabase()
{
setLayout(new FlowLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(6, 1, 0, 5));
p1.add(new JLabel("Name"));
p1.add(new JLabel("Address"));
p1.add(new JLabel("City"));
p1.add(new JLabel("State"));
p1.add(new JLabel("Major"));
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
clearAllFields();
}
});
p1.add(clearButton);
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(6, 1, 0, 5));
p2.add(nameField);
p2.add(addressField);
p2.add(cityField);
p2.add(stateField);
p2.add(majorField);
JButton enterButton = new JButton("Enter");
enterButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
Student tempStudent = new Student(
nameField.getText(),
addressField.getText(),
cityField.getText(),
stateField.getText(),
majorField.getText());
/* search list for a matching record
for
tempStudent.equals(i);
*/
int index = studio.compareStudent(tempStudent);
if(index < 0)
studio.addStudent(tempStudent);
else
{
new UpdateDialog(index, tempStudent);
}
clearAllFields();
}
});
p2.add(enterButton);
add(p1);
add(p2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
studio.save();
System.exit(0);
}
});
setSize(333,225);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
/*
dialog box with actionlitsteners for buttons
Lables for new and old studetns info
*/
class UpdateDialog extends JDialog
{
//where and why should these variables be??
private Student s;
private int index;
JLabel nameNew,addressNew,cityNew,stateNew,majorNew;
JLabel nameOld,addressOld,cityOld,stateOld,majorOld;
UpdateDialog(int i, Student tempStudent)
{
//some variables used in this class
this.s = tempStudent;
this.index = i;
//nested layouts:: flow has two gridlayouts with init
setLayout(new GridLayout(1,2));
//first panel is on top
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(7, 1, 0, 5));
//second pannel is on the bottom of the top pannel
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(7, 1, 0, 5));
//set the labels for NEW student info
nameNew = new JLabel(s.getName());
addressNew = new JLabel(s.getAddress());
cityNew = new JLabel(s.getCity());
stateNew = new JLabel(s.getState());
majorNew = new JLabel(s.getMajor());
//set the labels for OLD student info
nameOld = new JLabel(studio.getStudent(index).getName());
addressOld = new JLabel(studio.getStudent(index).getAddress());
cityOld = new JLabel(studio.getStudent(index).getCity());
stateOld = new JLabel(studio.getStudent(index).getState());
majorOld = new JLabel(studio.getStudent(index).getMajor());
//buttons and their listeners
//ok button
JButton okButton = new JButton( "OK" );
okButton.setBackground(Color.GREEN);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
/* delete and replace student record */
studio.removeStudent(index);
studio.addStudent(s);
dispose();
}
});
//cancel button
JButton cancelButton = new JButton( "Cancel" );
cancelButton.setBackground(Color.RED);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dispose();
}
});
//addlables and buttons to Left pannles
leftPanel.add(new Label("New Student"));
leftPanel.add(nameNew);
leftPanel.add(addressNew);
leftPanel.add(cityNew);
leftPanel.add(stateNew);
leftPanel.add(majorNew);
leftPanel.add(okButton);
//addlables and buttons to Right pannles
rightPanel.add(new Label("Old Student"));
rightPanel.add(nameOld);
rightPanel.add(addressOld);
rightPanel.add(cityOld);
rightPanel.add(stateOld);
rightPanel.add(majorOld);
rightPanel.add(cancelButton);
//add panels to frame
add(leftPanel);
add(rightPanel);
//window attributes
setModal(true);
setSize(250,190);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}
void clearAllFields()
{
nameField.setText("");
addressField.setText("");
cityField.setText("");
stateField.setText("");
majorField.setText("");
}
public static void main(String[] args)
{
StudentDatabase frame = new StudentDatabase();
}
}
class Student implements Comparable
{
private String name, address, city, state, major;
public Student(String name, String address, String city, String state,
String major)
{
this.name = name;
this.address = address;
this.city = city;
this.state = state;
this.major = major;
}
public String toString()
{
return (
name + "\n" +
address + "\n" +
city + "\n" +
state + "\n" +
major + "\n");
}
public int compareTo(Object o)
{
return name.compareTo(((Student)o).name);
}
public boolean equals(Object s)
{
return name.equalsIgnoreCase(((Student)s).name);
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getMajor()
{
return major;
}
}
class StudentIO
{
//private File file;
private ArrayList<Student> list = new ArrayList();
private Scanner in;
private PrintWriter pw;
//private String name, address, city, state, major;
/*load student object into arralist
-accept file
-create scanner using file
-load sutdents from file if there are any students
*/
public StudentIO(File file)
{
if(file.exists())
{
try
{
this.in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
do
{
list.add(getStudentFromFile(file));
in.nextLine();
} while(in.hasNext());
System.out.println(list.size() + " entries read.");
}
try
{
this.pw = new PrintWriter(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
private Student getStudentFromFile(File file)
{
return
//calls constructor from Student Class
new Student
(
in.nextLine(),
in.nextLine(),
in.nextLine(),
in.nextLine(),
in.nextLine()
);
}
public void save()
{
for(int i = 0; i < list.size(); i++)
{
pw.println(list.get(i));
}
System.out.println("File saved.");
pw.close();
}
public int compareStudent(Student s)
{
for(int i = 0; i < list.size(); i++)
{
if(s.equals(list.get(i)))
return i;
}
return -1;
}
public void removeStudent(int i)
{
list.remove(i);
}
public void addStudent(Student s)
{
list.add(s);
}
public Student getStudent(int index)
{
return list.get(index);
}
}
__________________
i dont know much about programming but i try to help |
|
|
|
|
|
#2 |
|
Sexy Programmer
|
I like it. Looks nice. Works great. Only a few things I would suggest:
Look up Object Serialization. Also, add another feature that would enable a user to view all of the students currently in the database.
__________________
I would love to change the world, but they won't give me the source code! |
|
|
|
|
|
#3 |
|
Professional Programmer
|
Get rid of all the obvious comments. Stuff like "declare the name..." or "create a new IO object".
Anything that is overly obvious. |
|
|
|
|
|
#4 |
|
Hobbyist Programmer
|
:beard: In my opinion you can never have too many comments. At least in the places where he doesn't just say "declare the name" but where he also tells what it will be used for, which I believe is a good thing to do, but to each his own I guess.
__________________
I have never let my schooling interfere with my education. -Mark Twain- Xbox live gamertag: melbolt Last edited by melbolt; Apr 24th, 2007 at 8:13 AM. |
|
|
|
|
|
#5 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Obvious comments just trash up the joint. Here's an example I recently encountered:
int getWords (char *ptr2) //FUNCTION no kidding! ...snip... while (!check)//WHILE LOOP really! ... In my view, comments are good for describing an algorithm or the function of an entire section of code whose overall purpose may not be immediately clear when reading it, line by line.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#6 | |
|
Hobbyist Programmer
|
Quote:
Yes, that is the requirement for the class I am in. We are to do top down outline like commenting for functions. I have yet to do that part. I will repost the code when I fish cleaning it up and we can further the commenting disgustion.
__________________
i dont know much about programming but i try to help |
|
|
|
|
|
|
#7 |
|
Hobbyist Programmer
|
here is the final cleaned up commented version
// Assignmet 2
//Seth Wildstone and Chris Martin
//4-26-07
//Swing GUI student data base manager
//reads a file into memroy then users enter student info. if the same name is entered
//the user is prompted to overwrite the student info. user can choose to overwrite
//or not. data is saved to file when exiting.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class StudentDatabase extends JFrame
{
// declare the name of the text file that stores the student datatbase
private final File STUDIO_FILE = new File("studio.txt");
// create an IO object for the database file
private StudentIO studio = new StudentIO(STUDIO_FILE);
// declare the GUI text fields. out here b/c used by clear method
private JTextField nameField = new JTextField(20);
private JTextField addressField = new JTextField(20);
private JTextField cityField = new JTextField(20);
private JTextField stateField = new JTextField(20);
private JTextField majorField = new JTextField(20);
// default Student Database constructor
public StudentDatabase()
{
/*
-set layout to flow with two panels
-left panel JLables
-right panel TextFields
-make buttons and listeners
-add componates to panels
-add panels to frame
-set window atributes
*/
setLayout(new FlowLayout());
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(6, 1, 0, 5));
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(6, 1, 0, 5));
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
clearAllFields();
}
});
JButton enterButton = new JButton("Enter");
enterButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
Student tempStudent = new Student(
//instanciate a new Student object by getting strings
//from textfields
nameField.getText(),
addressField.getText(),
cityField.getText(),
stateField.getText(),
majorField.getText());
/*
-compareStudent is a methdon in StudentIO
-studio is an instance of StudnetIO class
-send the tempStudent object to compareStudent
-this returns the index of the match in the ArrayList
-OR returns -1 if no match is found
-index is assigned the returned value
-if no match found,meaning no previous entry add the
-current tempStudent
-if match found pop up dialong box asking to add new or ignore
-call method clearAllFields to empty the TextFields
*/
int index = studio.compareStudent(tempStudent);
if(index < 0)
studio.addStudent(tempStudent);
else
new UpdateDialog(index, tempStudent);
clearAllFields();
}
});
//listen for closing. save file when closing happens
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
studio.save();
System.exit(0);
}
});
//add JLabels to left panel
leftPanel.add(new JLabel("Name"));
leftPanel.add(new JLabel("Address"));
leftPanel.add(new JLabel("City"));
leftPanel.add(new JLabel("State"));
leftPanel.add(new JLabel("Major"));
leftPanel.add(clearButton);
//add JLabels to right panel
rightPanel.add(nameField);
rightPanel.add(addressField);
rightPanel.add(cityField);
rightPanel.add(stateField);
rightPanel.add(majorField);
rightPanel.add(enterButton);
//add panels to frame
add(leftPanel);
add(rightPanel);
//set frame atributes
setSize(333,225);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}//END CONSTRUCTOR
class UpdateDialog extends JDialog
{
private Student newStudent;
private int index; //from compareStudent in StudentIO
private Student oldStudent;
private JLabel nameNew,addressNew,cityNew,stateNew,majorNew;
private JLabel nameOld,addressOld,cityOld,stateOld,majorOld;
UpdateDialog(int i, Student tempStudent)
{
/*
-assign index and lbject varriables
-set the layout to a 1x2 Grid that has two panels with 7x1 grids in ea.
-assign ond and new student info to JLabels
-creat OK and Cancel buttons with actionListeners
-add lables and buttons to pannles
-add panels to frame
-set window attributes
*/
this.newStudent = tempStudent;
//point to the loaction in the arraylist where match was found
this.index = i;
//"temp" holder object for the matched old student info
this.oldStudent = studio.getStudent(index);
//nested layouts:: gridLayout has two gridlayouts with in it
setLayout(new GridLayout(1,2));
//first panel is on the left
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(7, 1, 0, 5));
//second pannel is on the right
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(7, 1, 0, 5));
//set the labels for NEW student info
nameNew = new JLabel(newStudent.getName());
addressNew = new JLabel(newStudent.getAddress());
cityNew = new JLabel(newStudent.getCity());
stateNew = new JLabel(newStudent.getState());
majorNew = new JLabel(newStudent.getMajor());
//set the labels for OLD student info
nameOld = new JLabel(oldStudent.getName());
addressOld = new JLabel(oldStudent.getAddress());
cityOld = new JLabel(oldStudent.getCity());
stateOld = new JLabel(oldStudent.getState());
majorOld = new JLabel(oldStudent.getMajor());
//ok button and listener. adds new student info to list
JButton okButton = new JButton( "OK" );
okButton.setBackground(Color.GREEN);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
/* delete and replace student record */
studio.removeStudent(index);
studio.addStudent(newStudent);
dispose();
}
});
//cancel button and listener. closes the dialog box
JButton cancelButton = new JButton( "Cancel" );
cancelButton.setBackground(Color.RED);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dispose();
}
});
//add lables and buttons to Left pannles
leftPanel.add(new Label("New Student"));
leftPanel.add(nameNew);
leftPanel.add(addressNew);
leftPanel.add(cityNew);
leftPanel.add(stateNew);
leftPanel.add(majorNew);
leftPanel.add(okButton);
//add lables and buttons to Right pannles
rightPanel.add(new Label("Old Student"));
rightPanel.add(nameOld);
rightPanel.add(addressOld);
rightPanel.add(cityOld);
rightPanel.add(stateOld);
rightPanel.add(majorOld);
rightPanel.add(cancelButton);
//add panels to frame
add(leftPanel);
add(rightPanel);
//set window attributes
setModal(true);
setSize(250,190);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}
void clearAllFields()
//set all textfields to empty strings. removes old text.
{
nameField.setText("");
addressField.setText("");
cityField.setText("");
stateField.setText("");
majorField.setText("");
}
public static void main(String[] args)
{
StudentDatabase frame = new StudentDatabase();
}
}
//do we need coments for the constuctor??
class Student
{
private String name, address, city, state, major;
public Student(String name, String address, String city, String state,
String major)
{
this.name = name;
this.address = address;
this.city = city;
this.state = state;
this.major = major;
}
public boolean equals(Object s)
/*
-accept object
-type cast object to Student object
-compare the instance name to the passed object name
-return true if names are the same
-return false if names are not the same
*/
{
return name.equalsIgnoreCase(((Student)s).name);
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getMajor()
{
return major;
}
public String toString()
//!!!THIS IS NEED TO WRITE TEXT TO FILE!!!
//!!!EXLUDING IT WILL WRITE OBJECT HASH CODE!!!!!!
{
return name + "\n" +
address + "\n" +
city + "\n" +
state + "\n" +
major + "\n";
}
}
class StudentIO
{
private File file;
private ArrayList<Student> list = new ArrayList();
private Scanner in;
private PrintWriter pw;
public StudentIO(File file)
{
/*load student object into arralist
-accept file
-create scanner using file
-load sutdents from file if there are any students
-say how may studetns were read in
-creat printwrite object to use later save to file
*/
if(file.exists())
{
try
{
this.in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
do
{
list.add(getStudentFromFile(file));
in.nextLine();
} while(in.hasNext());
System.out.println(list.size() + " entries read.");
}
try
{
this.pw = new PrintWriter(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
private Student getStudentFromFile(File file)
{
/*
-accept file to read from
-making a new student object
-read in text lines from file
-return new Student object
*/
return
new Student
(
in.nextLine(),
in.nextLine(),
in.nextLine(),
in.nextLine(),
in.nextLine()
);
}
public void save()
{
/*Save the arrayList to file
-go thru the entire arraylist
-write each object in arraylist to file
-promt that file has been saved
-close file
*/
for(int i = 0; i < list.size(); i++)
{
pw.println(list.get(i));
}
System.out.println("File saved.");
pw.close();
}
public int compareStudent(Student s)
/*
-accepts a student object
-use the equals method from Student class
-compares passed student object to all elements in the ArrayList
-if no match if found return -1 indicating that dialog box need not pop
-if match found return index in the ArrayLIst.
*/
{
for(int i = 0; i < list.size(); i++)
{
if(s.equals(list.get(i)))
return i;
}
return -1;
}
public void removeStudent(int i)
{
list.remove(i);
}
public void addStudent(Student s)
{
list.add(s);
}
public Student getStudent(int index)
{
return list.get(index);
}
}
__________________
i dont know much about programming but i try to help |
|
|
|
|
|
#8 |
|
Battle Programmer
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 766
Rep Power: 3
![]() |
If I might suggest, use Javadocs to document your functions, and keep your commenting consistent (there's one spot where the comment comes between the method name and the opening brace). While your outline form isn't necessarily bad, I personally find a stricter styling easier to read (e.g. @param tags will tell you all the parameters, and then have a sentence or paragraph describing a what the class/method does). Personal preference, mind you, but that's how I'd do it.
__________________
<insert disclaimer here> <insert shameless plug for Visual Studio here> |
|
|
|
|
|
#9 |
|
Hobbyist Programmer
|
we never had to do that. infact i dont know how to do it. the instructor breifly showed us some commenting "syntax" that generated docs once.
__________________
i dont know much about programming but i try to help |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| EXECryptor software protection | Jean5 | C++ | 35 | Oct 10th, 2006 7:10 PM |
| Little help | whoawhoayoyo | Assembly | 8 | Apr 18th, 2006 7:10 PM |
| How to post a question | nnxion | C++ | 10 | Jun 3rd, 2005 11:53 AM |
| How to post a question | nnxion | C++ | 0 | Jun 3rd, 2005 8:55 AM |
| How to post a question | nnxion | C | 0 | Jun 3rd, 2005 8:55 AM |