I am stuck with this code- I definitely need a bail out

I would appreciate if a good samaritan could add this code for me. I am at my wits end.
The program I am trying to write is supposed to add students with their personal information and then display them in a GUI.
I should be able to select a student and add a grade for that student.
Finally I should be able to get the average for all the grades added for this student and display the average grade.
My challenge is how to obtain all the added scores and show the students average .
I understand my best shot is to use VECTOR API.
I tried to write someething but it did not work at , obviously due to inexperience.
I just can't figure how to link this average display window to the Get Average button.
A student can have any number of grades.
I need someone to show me the way, may be little "code guide" I am waaaay lost
Thanks in advance
Little Delmarie.
THIS IS WHAT I HAVE DONE SO FAR . IT COMPILES nicely in DOS and Visual age
// CODE GradeSystem
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
* UsingJLists.java
* This is a sample program for the use of JLists. You can add a student by entering their
* information a clicking on add. You can remove a student by entering their information and
* clicking on remove. They must be in the list to be removed. You can modify a student by
* entering their information and clicking add. You will be asked for the new student
* information when using modify. The add and remove buttons will disappear when modifying
* is underway and the new information is being collected for updating.
* @author Delmarie
public class GradeSystem extends JDialog {
Vector studentGrades = new Vector();
JButton add, modify, remove;
JList theJList;
JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
JTextField score, possibleScore, gradeType;
JLabel label1, label2, label3;
public class ModifyHandler implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
// get the student info from the text boxes
double dScore = 0;
double dPossibleScore = 0;
try {
String str1 = score.getText();
if (str1 != null) dScore = Double.parseDouble(str1);
String str2 = possibleScore.getText();
if (str2 != null) dPossibleScore = Double.parseDouble(str2);
catch(NumberFormatException e) {}
String sGradeType = gradeType.getText();
Grade grade = (Grade)theJList.getSelectedValue();
if (grade == null) {
score.setText("");
possibleScore.setText("");
gradeType.setText("");
return;
grade.setScore(dScore);
grade.setPossibleScore(dPossibleScore);
grade.setGradeType(sGradeType);
theJList.repaint();
public class RemoveHandler implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
int removeIndex = theJList.getSelectedIndex();
if (removeIndex == -1) {
score.setText("");
possibleScore.setText("");
gradeType.setText("");
return;
DefaultListModel model = (DefaultListModel) theJList.getModel();
model.removeElementAt(removeIndex);
studentGrades.removeElementAt(removeIndex);
// clear the textboxes
score.setText("");
possibleScore.setText("");
gradeType.setText("");
public class AddHandler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
// get the student info from the text boxes
double dScore = 0;
double dPossibleScore = 0;
try {
String str1 = score.getText();
if (str1 != null) dScore = Double.parseDouble(str1);
String str2 = possibleScore.getText();
if (str2 != null) dPossibleScore = Double.parseDouble(str2);
catch(NumberFormatException e) {}
String sGradeType = gradeType.getText();
// get the model and add the student to the model
Grade g = new Grade();
g.setScore(dScore);
g.setPossibleScore(dPossibleScore);
g.setGradeType(sGradeType);
studentGrades.add(g);
DefaultListModel model = (DefaultListModel) theJList.getModel();
model.addElement(g);
// display the added element
theJList.setSelectedValue(g, true);
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
setVisible(false);
/** Creates a new instance of UsingJLists */
public GradeSystem(JFrame owner, boolean modal) {
super(owner, modal);
// create all of the components, put them in panels, and put the panels in JFrame
add = new JButton("Add");
modify = new JButton("Modify");
remove = new JButton("Remove");
score = new JTextField("");
score.setColumns(10);
possibleScore = new JTextField("");
gradeType = new JTextField("");
label1 = new JLabel("score");
label2 = new JLabel("possibleScore");
label3 = new JLabel("gradeType");
FlowLayout flow = new FlowLayout();
FlowLayout flow1 = new FlowLayout();
FlowLayout flow2 = new FlowLayout();
GridLayout grid1 = new GridLayout(7,1);
GridLayout grid2 = new GridLayout(7,1);
BorderLayout border3 = new BorderLayout();
buttonPanel = new JPanel(flow);
buttonPanel.add(add);
buttonPanel.add(modify);
buttonPanel.add(remove);
labelPanel = new JPanel(grid1);
//labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label1);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label2);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label3);
labelPanel.add(Box.createVerticalStrut(20));
textPanel = new JPanel(grid2);
//textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(score);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(possibleScore);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(gradeType);
textPanel.add(Box.createVerticalStrut(20));
infoPanel = new JPanel(new FlowLayout());
infoPanel.setBorder(BorderFactory.createTitledBorder("Grade Information"));
infoPanel.add(Box.createHorizontalStrut(10));
infoPanel.add(textPanel);
infoPanel.add(Box.createHorizontalStrut(10));
infoPanel.add(labelPanel);
infoPanel.add(Box.createHorizontalStrut(10));
theJList = new JList(new DefaultListModel());
theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
public void valueChanged(ListSelectionEvent evt) {
Grade grade = (Grade)theJList.getSelectedValue();
if (grade == null) {
score.setText("");
possibleScore.setText("");
gradeType.setText("");
return;
score.setText(Double.toString(grade.getScore()));
possibleScore.setText(Double.toString(grade.getPossibleScore()));
gradeType.setText(grade.getGradeType());
//JLabel theLabel = new JLabel("Students");
jlistPanel = new JPanel(border3);
jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Scores"));
jlistPanel.add(new JScrollPane(theJList));//, BorderLayout.SOUTH);
masterPanel = new JPanel(new GridLayout(1, 2));
masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
// masterPanel.add(Box.createHorizontalStrut(10));
masterPanel.add(infoPanel);
// masterPanel.add(Box.createHorizontalStrut(10));
masterPanel.add(jlistPanel);
// masterPanel.add(Box.createHorizontalStrut(10));
BorderLayout border = new BorderLayout();
this.getContentPane().setLayout(border);
Container theContainer = this.getContentPane();
theContainer.add(buttonPanel,BorderLayout.SOUTH);
theContainer.add(masterPanel, BorderLayout.CENTER);
// now add the event handlers for the buttons
AddHandler handleAdd = new AddHandler();
ModifyHandler handleModify = new ModifyHandler();
RemoveHandler handleRemove = new RemoveHandler();
add.addActionListener(handleAdd);
modify.addActionListener(handleModify);
remove.addActionListener(handleRemove);
// add the event handler for the window events
WindowHandler handleWindow = new WindowHandler();
this.addWindowListener(handleWindow);
setSize(600,300);
* Insert the method's description here.
* Creation date: (2/24/03 4:20:07 PM)
* @param v com.sun.java.util.collections.Vector
public void setStudentGrades(Vector v) {
studentGrades = v;
DefaultListModel model = (DefaultListModel) theJList.getModel();
model.removeAllElements();
int size = v.size();
for (int i = 0; i < size; i++) {
model.addElement(v.get(i));
score.setText("");
possibleScore.setText("");
gradeType.setText("");
setVisible(true);
// CODE2 StudentSystem
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
* UsingJLists.java
* This is a sample program for the use of JLists. You can add a student by entering their
* information a clicking on add. You can remove a student by entering their information and
* clicking on remove. They must be in the list to be removed. You can modify a student by
* entering their information and clicking add. You will be asked for the new student
* information when using modify. The add and remove buttons will disappear when modifying
* is underway and the new information is being collected for updating.
* @author Delmarie
public class StudentSystem extends JFrame {
StudentGradeBook studentGradeBook = new StudentGradeBook();
GradeSystem gradeSystem = new GradeSystem(this, true);
JButton add, modify, remove, bGrade;
JList theJList;
JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
JTextField name, address, email, phone, courseName, courseDescription;
JLabel label1, label2, label3;
StudentSystem tempObjectRef; // used to hold a class level reference to object for dispose
boolean getStudentInfo = false;
int saveIndexInObject;
public class ModifyHandler implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
// get the information for the student to modify
String studentName = name.getText();
String studentAddress = address.getText();
String studentEmail = email.getText();
if (!getStudentInfo) { // set up to get student info
// find the correct element of the model to remove and save in class variable
int removeIndex = -1;
DefaultListModel model = (DefaultListModel) theJList.getModel();
for (int i = 0; i < model.size(); i++) {
String temp = (String) model.elementAt(i);
if (temp.equals(name.getText())) {
removeIndex = i;
break;
saveIndexInObject = removeIndex;
if (removeIndex == -1) return;
// change the text on the border of the info box
infoPanel.setBorder(BorderFactory.createTitledBorder("Enter new Student Info"));
// set up to get the modified info and remove some of the buttons
getStudentInfo = true;
buttonPanel.removeAll();
buttonPanel.add(modify);
buttonPanel.add(bGrade);
buttonPanel.repaint();
else {
// reset the border and change the element at the provided index (from if above)
getStudentInfo = false;
infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
DefaultListModel model = (DefaultListModel) theJList.getModel();
model.setElementAt(name.getText(), saveIndexInObject);
Student student = studentGradeBook.findStudent(saveIndexInObject);
student.setName(name.getText());
student.setAddress(address.getText());
student.setEmail(email.getText());
student.setPhone(phone.getText());
student.setCourseName(courseName.getText());
student.setCourseDescription(courseDescription.getText());
// clear the textboxes
name.setText("");
address.setText("");
email.setText("");
phone.setText("");
courseName.setText("");
courseDescription.setText("");
// restore all of the buttons
buttonPanel.removeAll();
buttonPanel.add(add);
buttonPanel.add(modify);
buttonPanel.add(remove);
buttonPanel.add(bGrade);
buttonPanel.repaint();
public class RemoveHandler implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
// get the student info from the text boxes
String studentName = name.getText();
String studentAddress = address.getText();
String studentEmail = email.getText();
// find the element to remove by name (you could use email address etc also)
int removeIndex = -1; // = theJList.getSelectedIndex();
DefaultListModel model = (DefaultListModel) theJList.getModel();
for (int i = 0; i < model.size(); i++) {
String temp = (String) model.elementAt(i);
if (temp.equals(name.getText())) {
removeIndex = i;
break;
if (removeIndex == -1) return;
// remove the element at the index from the for loop
model.removeElementAt(removeIndex);
Student student = studentGradeBook.findStudent(removeIndex);
studentGradeBook.removeStudent(student);
// clear the textboxes
name.setText("");
address.setText("");
email.setText("");
phone.setText("");
courseName.setText("");
courseDescription.setText("");
public class AddHandler implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
// get the student info from the text boxes
String studentName = name.getText();
String studentAddress = address.getText();
String studentEmail = email.getText();
String studentPhone = phone.getText();
String studentCourseName = courseName.getText();
String studentCourseDescription = courseDescription.getText();
// get the model and add the student to the model
studentGradeBook.addStudent(studentName, studentAddress, studentEmail, studentPhone,
studentCourseName, studentCourseDescription);
DefaultListModel model = (DefaultListModel) theJList.getModel();
model.addElement(studentName);
// reset the text boxes
name.setText("");
address.setText("");
email.setText("");
phone.setText("");
courseName.setText("");
courseDescription.setText("");
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
gradeSystem.dispose();
tempObjectRef.dispose();
System.exit(0);
/** Creates a new instance of UsingJLists */
public StudentSystem() {
// create all of the components, put them in panels, and put the panels in JFrame
add = new JButton("Add");
modify = new JButton("Modify");
remove = new JButton("Remove");
bGrade = new JButton("Grades");
name = new JTextField("");
name.setColumns(10);
address = new JTextField("");
email = new JTextField("");
phone = new JTextField("");
courseName = new JTextField("");
courseDescription = new JTextField("");
label1 = new JLabel("name");
label2 = new JLabel("address");
label3 = new JLabel("email");
JLabel label4 = new JLabel("phone");
JLabel label5 = new JLabel("courseName");
JLabel label6 = new JLabel("courseDescription");
FlowLayout flow = new FlowLayout();
FlowLayout flow1 = new FlowLayout();
FlowLayout flow2 = new FlowLayout();
GridLayout grid1 = new GridLayout(13,1);
GridLayout grid2 = new GridLayout(13,1);
BorderLayout border3 = new BorderLayout();
buttonPanel = new JPanel(flow);
buttonPanel.add(add);
buttonPanel.add(modify);
buttonPanel.add(remove);
buttonPanel.add(bGrade);
bGrade.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = theJList.getSelectedIndex();
if (index == -1) return;
Student student = studentGradeBook.findStudent(index);
gradeSystem.setStudentGrades(student.getStudentGrades());
labelPanel = new JPanel(grid1);
//labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label1);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label2);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label3);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label4);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label5);
labelPanel.add(Box.createVerticalStrut(20));
labelPanel.add(label6);
labelPanel.add(Box.createVerticalStrut(20));
textPanel = new JPanel(grid2);
//textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(name);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(address);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(email);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(phone);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(courseName);
textPanel.add(Box.createVerticalStrut(20));
textPanel.add(courseDescription);
textPanel.add(Box.createVerticalStrut(20));
infoPanel = new JPanel(new FlowLayout());
infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
infoPanel.add(Box.createHorizontalStrut(10));
infoPanel.add(textPanel);
infoPanel.add(Box.createHorizontalStrut(10));
infoPanel.add(labelPanel);
infoPanel.add(Box.createHorizontalStrut(10));
theJList = new JList(new DefaultListModel());
theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
public void valueChanged(ListSelectionEvent evt) {
int index = theJList.getSelectedIndex();
if (index == -1) return;
Student student = studentGradeBook.findStudent(index);
name.setText(student.getName());
address.setText(student.getAddress());
email.setText(student.getEmail());
phone.setText(student.getPhone());
courseName.setText(student.getCourseName());
courseDescription.setText(student.getCourseDescription());
//JLabel theLabel = new JLabel("Students");
jlistPanel = new JPanel(border3);
jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Students"));
jlistPanel.add(new JScrollPane(theJList), BorderLayout.SOUTH);
masterPanel = new JPanel(flow1);
masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
masterPanel.add(Box.createHorizontalStrut(10));
masterPanel.add(infoPanel);
masterPanel.add(Box.createHorizontalStrut(10));
masterPanel.add(jlistPanel);
masterPanel.add(Box.createHorizontalStrut(10));
BorderLayout border = new BorderLayout();
this.getContentPane().setLayout(border);
Container theContainer = this.getContentPane();
theContainer.add(buttonPanel,BorderLayout.SOUTH);
theContainer.add(masterPanel, BorderLayout.NORTH);
// now add the event handlers for the buttons
AddHandler handleAdd = new AddHandler();
ModifyHandler handleModify = new ModifyHandler();
RemoveHandler handleRemove = new RemoveHandler();
add.addActionListener(handleAdd);
modify.addActionListener(handleModify);
remove.addActionListener(handleRemove);
// add the event handler for the window events
WindowHandler handleWindow = new WindowHandler();
this.addWindowListener(handleWindow);
// make the frame visible and set its size and show it.
this.setVisible(true);
this.pack();//setSize(600,300);
this.show();
public static void main (String [] args) {
StudentSystem mainObject = new StudentSystem();
mainObject.setTempObjectRef(mainObject);
public void setTempObjectRef(StudentSystem obj) {
// set up a reference to this object for use in closing the window method dispose
tempObjectRef = obj;
// CODE 3 Student
import java.util.*;
* Insert the type's description here.
* Creation date: (2/24/03 11:23:58 AM)
* @author: Delmarie
public class Student {
private String name, address, phone, email, courseName, courseDescription;
private Vector studentGrades;
* Student constructor comment.
public Student() {
studentGrades = new Vector();
* Insert the method's description here.
* Creation date: (2/24/03 11:39:56 AM)
* @param score double
* @param possibleScore double
* @param gradeType java.lang.String
public void addGrade(double score, double possibleScore, String gradeType) {
Grade g = new Grade();
g.setScore(score);
g.setPossibleScore(possibleScore);
g.setGradeType(gradeType);
studentGrades.add(g);
* Insert the method's description here.
* Creation date: (2/24/03 11:47:01 AM)
* @return Grade
* @param index int
public Grade findGrade(int index) {
return (Grade)studentGrades.get(index);
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getAddress() {
return address;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getCourseDescription() {
return courseDescription;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getCourseName() {
return courseName;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getEmail() {
return email;
* Insert the method's description here.
* Creation date: (2/24/03 11:48:03 AM)
* @return java.util.Iterator
public Iterator getGradeIterator() {
return studentGrades.iterator();
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getName() {
return name;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @return java.lang.String
public java.lang.String getPhone() {
return phone;
* Insert the method's description here.
* Creation date: (2/25/03 10:56:13 AM)
* @return java.util.Vector
public java.util.Vector getStudentGrades() {
return studentGrades;
* Insert the method's description here.
* Creation date: (2/24/03 11:41:52 AM)
* @param grade Grade
public void removeGrade(Grade grade) {
studentGrades.remove(grade);
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newAddress java.lang.String
public void setAddress(java.lang.String newAddress) {
address = newAddress;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newCourseDescription java.lang.String
public void setCourseDescription(java.lang.String newCourseDescription) {
courseDescription = newCourseDescription;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newCourseName java.lang.String
public void setCourseName(java.lang.String newCourseName) {
courseName = newCourseName;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newEmail java.lang.String
public void setEmail(java.lang.String newEmail) {
email = newEmail;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newName java.lang.String
public void setName(java.lang.String newName) {
name = newName;
* Insert the method's description here.
* Creation date: (2/24/03 11:28:57 AM)
* @param newPhone java.lang.String
public void setPhone(java.lang.String newPhone) {
phone = newPhone;
* Insert the method's description here.
* Creation date: (2/25/03 10:56:13 AM)
* @param newStudentGrades java.util.Vector
public void setStudentGrades(Vector newStudentGrades) {
studentGrades = newStudentGrades;
//CODE 4 StudentGradeBook
import java.util.*;
* Insert the type's description here.
* Creation date: (2/24/03 11:50:35 AM)
* @author: delmarie
public class StudentGradeBook {
private Vector allStudents;
* StudentGradeBook constructor comment.
public StudentGradeBook() {
allStudents = new Vector();
* Insert the method's description here.
* Creation date: (2/24/03 11:54:01 AM)
* @param name java.lang.String
* @param address java.lang.String
* @param email java.lang.String
* @param phone java.lang.String
public void addStudent(String name, String address, String email, String phone) {
Student student = new Student();
student.setName(name);
student.setAddress(address);
student.setEmail(email);
student.setPhone(phone);
allStudents.add(student);
* Insert the method's description here.
* Creation date: (2/24/03 11:54:01 AM)
* @param name java.lang.String
* @param address java.lang.String
* @param email java.lang.String
* @param phone java.lang.String
public void addStudent(String name, String address, String email, String phone,
String courseName, String courseDescription) {
Student student = new Student();
student.setName(name);
student.setAddress(address);
student.setEmail(email);
student.setPhone(phone);
student.setCourseName(courseName);
student.setCourseDescription(courseDescription);
allStudents.add(student);
* Insert the method's description here.
* Creation date: (2/24/03 12:00:53 PM)
* @param index Student
public Student findStudent(int index) {
return (Student)allStudents.get(index);
* Insert the method's description here.
* Creation date: (2/24/03 12:02:43 PM)
* @return java.util.Iterator
public Iterator getStudentIterator() {
return allStudents.iterator();
* Insert the method's description here.
* Creation date: (2/24/03 11:59:41 AM)
* @param student Student
public void removeStudent(Student student) {
allStudents.remove(student);
// CODE 5 Grade
* Insert the type's description here.
* Creation date: (2/24/03 11:29:38 AM)
* @author: Delmarie
public class Grade {
private double score, possibleScore;
private String gradeType;
* Insert the method's description here.
* Creation date: (2/24/03 11:46:07 AM)
public Grade() {}
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @return java.lang.String
public java.lang.String getGradeType() {
return gradeType;
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @return double
public double getPossibleScore() {
return possibleScore;
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @return double
public double getScore() {
return score;
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @param newGradeType java.lang.String
public void setGradeType(java.lang.String newGradeType) {
gradeType = newGradeType;
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @param newPossibleScore double
public void setPossibleScore(double newPossibleScore) {
possibleScore = newPossibleScore;
* Insert the method's description here.
* Creation date: (2/24/03 11:31:13 AM)
* @param newScore double
public void setScore(double newScore) {
score = newScore;
* Insert the method's description here.
* Creation date: (2/24/03 4:03:57 PM)
* @return java.lang.String
public String toString() {
return Double.toString(score);

Ok.
I had a look at your code and decided against showing you how to
modify it to do what you want....
Reason being that it's something of a mess. I guess the reason for that
mess is a combination of the fact that you're new to Java (new to
software in general?) and you're using Visual Age.
So, below is a very quick (far from perfect, I just knocked it up in my
lunch hour) example of the kind of approach I would take to the problem.
Feel free to take ideas from it and build them in to your code.
Whatever you do, don't hand it in as you own work. By all means, hand
it in in addition to your own work and maybe even get your
teacher to comment on it.
Oh yes, if you use it, chuck me some dukes form this and your earlier
post on the same subject. Too many folks these days are neglecting to
allocate dukes - don't be one of them!
Oh, one thing about using the app, double clicking on table entries
for students and grades brings up the appropriate dialog. To create
a new grade or delete the selected ones, use the "right mouse" context
menu.
Enjoy.
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class Rosemary2
     static class GradeDialog
          extends JDialog
          private JTextField mScore= new JTextField();
          private JTextField mPossibleScore= new JTextField();
          private JTextField mGradeType= new JTextField();
          private Grade mGrade;
          public GradeDialog(JDialog owner) { this(owner, null); }
          public GradeDialog(JDialog owner, Grade grade)
               super(owner, true);
               mGrade= grade;
               if (mGrade == null)
                    setTitle("New Grade");
               else {
                    setTitle("Edit Grade");
                    setGrade();
               JPanel panel= new JPanel();
               panel.setBorder(new EmptyBorder(4,4,4,4));
               panel.setLayout(new GridLayout(0,2,4,4));
               panel.add(new JLabel("Score:"));
               panel.add(mScore);
               panel.add(new JLabel("Possible Score:"));
               panel.add(mPossibleScore);
               panel.add(new JLabel("Grade Type:"));
               panel.add(mGradeType);
               getContentPane().add(panel, BorderLayout.CENTER);
               panel= new JPanel();
               panel.setLayout(new GridLayout(1,0));
               JButton ok= new JButton("OK");
               panel.add(ok);
               ok.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         if (scrapeGrade())
                              dispose();
               JButton cancel= new JButton("Cancel");
               panel.add(cancel);
               cancel.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         mGrade= null;
                         dispose();
               JPanel wrapper= new JPanel();
               wrapper.setBorder(new EmptyBorder(0,4,4,4));
               wrapper.setLayout(new BorderLayout());
               wrapper.add(panel, BorderLayout.EAST);
               getContentPane().add(wrapper, BorderLayout.SOUTH);
               setResizable(false);
               pack();
               setLocation(
                    owner.getLocation().x +
                         (owner.getSize().width/2) -
                              (getSize().width/2),
                    owner.getLocation().y +
                         (owner.getSize().height/2) -
                              (getSize().height/2));
          private void setGrade()
               mScore.setText(String.valueOf(mGrade.getScore()));
               mPossibleScore.setText(String.valueOf(mGrade.getPossibleScore()));
               mGradeType.setText(mGrade.getGradeType());
               mScore.selectAll();
          private boolean scrapeGrade()
               try {
                    if (mGrade == null) {
                         mGrade= new Grade(
                              Double.parseDouble(mScore.getText()),
                              Double.parseDouble(mPossibleScore.getText()),
                              mGradeType.getText());
                    else {
                         mGrade.setScore(Double.parseDouble(mScore.getText()));
                         mGrade.setPossibleScore(Double.parseDouble(mPossibleScore.getText()));
                         mGrade.setGradeType(mGradeType.getText());
                    return true;
               catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "Scores must be numbers, you Muppet!");
               return false;
          public Grade getGrade() { return mGrade; }
     static class GradesPanel
          extends JPanel
          private Vector mGrades= new Vector();
          private JTable mTable;
          private NumberFormat mFormat= NumberFormat.getInstance();
          private JDialog mParent;
          public GradesPanel(JDialog parent, Iterator grades)
               mParent= parent;
               mFormat.setMaximumFractionDigits(2);
               while (grades != null && grades.hasNext())
                    mGrades.add(grades.next());
               setLayout(new BorderLayout());
               setBorder(new EmptyBorder(4,4,4,4));
               createTable();
               JScrollPane sp= new JScrollPane(mTable);
               add(sp, BorderLayout.CENTER);
               MouseListener listener= new MouseAdapter() {
                    public void mousePressed(MouseEvent e) {
                         if (e.getButton() == e.BUTTON2 || e.getButton() == e.BUTTON3)     
                              menu(e.getPoint());
               mTable.addMouseListener(listener);
               sp.addMouseListener(listener);
               mTable.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                         if (e.getClickCount() >= 2)
                              editGrade();
          public Iterator getGrades() { return mGrades.iterator(); }
          private void createTable()
               mTable= new JTable(new AbstractTableModel() {
                    public int getColumnCount() {
                         return 4;
                    public int getRowCount() {
                         return mGrades.size();
                    public String getColumnName(int column) {
                         switch (column) {
                              case 0: return "Score";
                              case 1: return "Possible";
                              case 2: return "Type";
                              case 3: return "Grade";
                              default: return "###";
                    public Object getValueAt(int row, int column) {
                         Grade grade= (Grade) mGrades.elementAt(row);
                         switch (column) {
                              case 0: return mFormat.format(grade.getScore());
                              case 1: return mFormat.format(grade.getPossibleScore());
                              case 2: return grade.getGradeType();
                              case 3: return String.valueOf(grade.getGrade()) +"%";
                              default: return "###";
               mTable.setPreferredScrollableViewportSize(new Dimension(10,10));
          private void menu(Point point)
               JPopupMenu popup= new JPopupMenu();
               JMenuItem add= new JMenuItem("Add");
               popup.add(add);
               add.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { addGrade(); } });
               if (mTable.rowAtPoint(point) >= 0 && mTable.rowAtPoint(point) == mTable.getSelectedRow()) {
                    JMenuItem edit= new JMenuItem("Edit");
                    popup.add(edit);
                    edit.addActionListener(new ActionListener() {
                         public void actionPerformed(ActionEvent e) { editGrade(); } });
                    if (mTable.getSelectedRowCount() > 1)
                         edit.setEnabled(false);
                    JMenuItem delete= new JMenuItem("Delete");
                    popup.add(delete);
                    delete.addActionListener(new ActionListener() {
                         public void actionPerformed(ActionEvent e) { deleteGrade(); } });
               popup.show(this, point.x, point.y);
          private void addGrade()
               GradeDialog dialog= new GradeDialog(mParent);
               dialog.setVisible(true);
               Grade grade= dialog.getGrade();
               if (grade != null) {
                    mGrades.add(grade);
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                         mGrades.size()-1, mGrades.size()-1);
          private void editGrade()
               GradeDialog dialog= new GradeDialog(
                    mParent, (Grade) mGrades.get(mTable.getSelectedRow()));
               dialog.setVisible(true);
               if (dialog.getGrade() != null) {
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                         mTable.getSelectedRow(), mTable.getSelectedRow());
          private void deleteGrade()
               while (true) {
                    int row= mTable.getSelectedRow();
                    if (row < 0)
                         break;
                    mGrades.removeElementAt(row);
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
     static class StudentDialog
          extends JDialog
          private JTextField mName= new JTextField(12);
          private JTextField mAddress= new JTextField();
          private JTextField mPhone= new JTextField();
          private JTextField mEmail= new JTextField();
          private JTextField mCourseName= new JTextField();
          private JTextField mCourseDescription= new JTextField();
          private GradesPanel mGradesPanel;
          private Student mStudent;
          public StudentDialog(JFrame owner) { this(owner, null); }
          public StudentDialog(JFrame owner, Student student)
               super(owner, true);
               mStudent= student;
               if (mStudent == null) {
                    setTitle("New Student");
                    mGradesPanel= new GradesPanel(this, null);
               else {
                    setTitle("Edit Student: " +mStudent.getName());
                    mGradesPanel= new GradesPanel(this, mStudent.getGrades());
               JTabbedPane tab= new JTabbedPane();
               tab.setBorder(new EmptyBorder(4,4,4,4));
               getContentPane().add(tab, BorderLayout.CENTER);
               tab.add("Details", getDetailsPanel());
               tab.add("Grades", mGradesPanel);
               JPanel panel= new JPanel();
               panel.setLayout(new GridLayout(1,0));
               JButton ok= new JButton("OK");
               panel.add(ok);
               ok.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         scrapeStudent();
                         dispose();
               JButton cancel= new JButton("Cancel");
               panel.add(cancel);
               cancel.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         mStudent= null;
                         dispose();
               JPanel wrapper= new JPanel();
               wrapper.setBorder(new EmptyBorder(0,4,4,4));
               wrapper.setLayout(new BorderLayout());
               wrapper.add(panel, BorderLayout.EAST);
               getContentPane().add(wrapper, BorderLayout.SOUTH);
               setResizable(false);
               pack();
               if (mStudent != null)
                    setStudent();
               setLocation(
                    owner.getLocation().x +
                         (owner.getSize().width/2) -
                              (getSize().width/2),
                    owner.getLocation().y +
                         (owner.getSize().height/2) -
                              (getSize().height/2));
          private JPanel getDetailsPanel()
               JPanel panel= new JPanel();
               panel.setBorder(new EmptyBorder(4,4,4,4));
               panel.setLayout(new GridLayout(0,2,4,4));
               panel.add(new JLabel("Name:"));
               panel.add(mName);
               panel.add(new JLabel("Address:"));
               panel.add(mAddress);
               panel.add(new JLabel("Phone:"));
               panel.add(mPhone);
               panel.add(new JLabel("E-Mail:"));
               panel.add(mEmail);
               panel.add(new JLabel("Course Name:"));
               panel.add(mCourseName);
               panel.add(new JLabel("Course Description:"));
               panel.add(mCourseDescription);
               return panel;
          private void setStudent()
               mName.setEnabled(false);
               mName.setText(mStudent.getName());
               mAddress.setText(mStudent.getAddress());
               mPhone.setText(mStudent.getPhone());
               mEmail.setText(mStudent.getEmail());
               mCourseName.setText(mStudent.getCourseName());
               mCourseDescription.setText(mStudent.getCourseDescription());
          private void scrapeStudent()
               if (mStudent == null) {
                    mStudent= new Student(
                         mName.getText(),
                         mAddress.getText(),
                         mPhone.getText(),
                         mEmail.getText(),
                         mCourseName.getText(),
                         mCourseDescription.getText());
               else {
                    mStudent.setName(mName.getText());
                    mStudent.setAddress(mAddress.getText());
                    mStudent.setPhone(mPhone.getText());
                    mStudent.setEmail(mEmail.getText());
                    mStudent.setCourseName(mCourseName.getText());
                    mStudent.setCourseDescription(mCourseDescription.getText());
               mStudent.clearGrades();
               Iterator grades= mGradesPanel.getGrades();
               while (grades.hasNext())
                    mStudent.addGrade((Grade) grades.next());
          public Student getStudent() { return mStudent; }
     static class StudentFrame
          extends JFrame
          private Vector mStudents;
          private JTable mTable;
          private JButton mBtnEdit;
          private JButton mBtnDelete;
          public StudentFrame(Vector students)
               super("Students");
               mStudents= students;
               createTable();
               getContentPane().add(new JScrollPane(mTable), BorderLayout.CENTER);
               JPanel panel= new JPanel();
               panel.setLayout(new GridLayout(1,0));
               JButton btn= new JButton("Add");
               panel.add(btn);
               btn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { addStudent(); } });
               mBtnEdit= new JButton("Edit");
               panel.add(mBtnEdit);
               mBtnEdit.setEnabled(false);
               mBtnEdit.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { editStudent(); } });
               mBtnDelete= new JButton("Delete");
               panel.add(mBtnDelete);
               mBtnDelete.setEnabled(false);
               mBtnDelete.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { deleteStudent(); } });
               JPanel wrapper= new JPanel();
               wrapper.setLayout(new BorderLayout());
               wrapper.add(panel, BorderLayout.WEST);
               getContentPane().add(wrapper, BorderLayout.SOUTH);
               btn= new JButton("Exit");
               wrapper.add(btn, BorderLayout.EAST);
               btn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) { System.exit(0); } });
               pack();
          private void createTable()
               mTable= new JTable(new AbstractTableModel() {
                    public int getColumnCount() {
                         return 7;
                    public int getRowCount() {
                         return mStudents.size();
                    public String getColumnName(int column) {
                         switch (column) {
                              case 0: return "Name";
                              case 1: return "Address";
                              case 2: return "Phone";
                              case 3: return "Email";
                              case 4: return "Course";
                              case 5: return "Description";
                              case 6: return "Grade Average";
                              default: return "###";
                    public Object getValueAt(int row, int column) {
                         Student student= (Student) mStudents.elementAt(row);
                         switch (column) {
                              case 0: return student.getName();
                              case 1: return student.getAddress();
                              case 2: return student.getPhone();
                              case 3: return student.getEmail();
                              case 4: return student.getCourseName();
                              case 5: return student.getCourseDescription();
                              case 6: return student.getGrade() >= 0 ? String.valueOf(student.getGrade()) +"%": "n/a";
                              default: return "###";
               mTable.getSelectionModel().addListSelectionListener(
                    new ListSelectionListener() {
                         public void valueChanged(ListSelectionEvent e) {
                              if (e.getValueIsAdjusting())
                                   return;
                              switch (mTable.getSelectedRowCount()) {
                                   case 0:
                                        mBtnEdit.setEnabled(false);
                                        mBtnDelete.setEnabled(false);
                                        break;
                                   case 1:
                                        mBtnEdit.setEnabled(true);
                                        mBtnDelete.setEnabled(true);
                                        break;
                                   default:
                                        mBtnEdit.setEnabled(false);
                                        mBtnDelete.setEnabled(true);
                                        break;
               mTable.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                         if (e.getClickCount() >= 2)
                              editStudent();
          private void addStudent()
               StudentDialog dialog= new StudentDialog(this);
               dialog.setVisible(true);
               Student student= dialog.getStudent();
               if (student != null) {
                    mStudents.add(student);
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                         mStudents.size()-1, mStudents.size()-1);
          private void editStudent()
               StudentDialog dialog= new StudentDialog(
                    this, (Student) mStudents.get(mTable.getSelectedRow()));
               dialog.setVisible(true);
               if (dialog.getStudent() != null) {
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                         mTable.getSelectedRow(), mTable.getSelectedRow());
          private void deleteStudent()
               while (true) {
                    int row= mTable.getSelectedRow();
                    if (row < 0)
                         break;
                    mStudents.removeElementAt(row);
                    ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
     static class Student
          private String name;
          private String address;
          private String phone ;
          private String email;
          private String courseName;
          private String courseDescription;
          private Vector grades= new Vector();
          public Student(
               String name,
               String address,
               String phone,
               String email,
               String courseName,
               String courseDescription)
               setName(name);
               setAddress(address);
               setPhone(phone);
               setEmail(email);
               setCourseName(courseName);
               setCourseDescription(courseDescription);
          public Iterator getGrades() { return grades.iterator(); }
          public void addGrade(Grade grade) { grades.add(grade); }
          public void removeGrade(Grade grade) { grades.remove(grade); }
          public void clearGrades() { grades.clear(); }
          public int getGrade()
               if (grades.size() == 0)
                    return -1;
               int total= 0;
               for (int i= 0; i< grades.size(); i++)
                    total += ((Grade) grades.get(i)).getGrade();
               return (int) (total/grades.size());
          public String getAddress() { return address; }
          public void setAddress(String newAddress) { address = newAddress; }
          public String getCourseDescription() { return courseDescription; }
          public void setCourseDescription(String newCourseDescription) { courseDescription = newCourseDescription; }
          public String getCourseName() { return courseName; }
          public void setCourseName(String newCourseName) { courseName = newCourseName; }
          public String getEmail() { return email; }
          public void setEmail(String newEmail) { email = newEmail; }
          public String getName() { return name; }
          public void setName(String newName) { name = newName; }
          public String getPhone() { return phone; }
          public void setPhone(String newPhone) { phone = newPhone; }
     static class Grade
          private double score;
          private double possibleScore;
          private String gradeType;
          public Grade(
               double score,
               double possibleScore,
               String gradeType)
               setScore(score);
               setPossibleScore(possibleScore);
               setGradeType(gradeType);
          public int getGrade() { return (int) ((100/possibleScore)*score); }
          public String getGradeType() { return gradeType; }
          public void setGradeType(String newGradeType) { gradeType = newGradeType; }
          public double getPossibleScore() { return possibleScore; }
          public void setPossibleScore(double newPossibleScore) { possibleScore = newPossibleScore; }
          public double getScore() { return score; }
          public void setScore(double newScore) { score = newScore; }
          public String toString() { return Double.toString(score); }
     public static void main (String [] args)
          Vector students= new Vector();
          students.add(new Student(
               "Fred Flitstone",
               "6 Boulder Close, Bedrock",
               "555 1234",
               "[email protected]",
               "Masonary 101",
               "Elementary chipping bits off rocks"));
          students.add(new Student(
               "Barney Rubble",
               "7 Boulder Close, Bedrock",
               "555 6789",
               "[email protected]",
               "Masonary 101",
               "Elementary chipping bits off rocks"));
          for (int i= 0; i< 10; i++) {
               Student student= new Student(
                    "Student " +i,
                    i +" Dorm St, Campus",
                    "555 1234",
                    "student" +i +"@college.edu",
                    "CS 101",
                    "CS for dummies");
               student.addGrade(new Grade(Math.random()*100, 100.0, "Passing?"));
               student.addGrade(new Grade(Math.random()*100, 100.0, "Failing?"));
               students.add(student);
          StudentFrame frame= new StudentFrame(students);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setBounds(32,32,640,480);
          frame.setVisible(true);
}

Similar Messages

  • Create code snippet with this code

    I'm curious...
    I can't create a code snippet with this code. (located in the first post)
    http://forums.ni.com/t5/LabVIEW/Event-structure-wi​th-value-changes/m-p/1937505#M646059
    However, I can create snippets from its sub-sections.
    Tried various versions of LabVIEW with the same result.
    Can anyone create a snippet?  Just curious.
    I'm not stuck or anything... just curious..  Maybe I should have posted in Breakpoint..
    Solved!
    Go to Solution.

    Spoiler (Highlight to read)
    I cheated and used my own Snippet tool.  Native tool dislike Event Structures.
    I cheated and used my own Snippet tool.  Native tool dislike Event Structures.

  • What is wrong with this code? on(release) gotoAndPlay("2")'{'

    Please could someone tell me what is wrong with this code - on(release)
    gotoAndPlay("2")'{'
    this is the error that comes up and i have tried changing it but it is not working
    **Error** Scene=Scene 1, layer=Layer 2, frame=1:Line 2: '{' expected
         gotoAndPlay("2")'{'
    Total ActionScript Errors: 1 Reported Errors: 1
    Thanks

    If you have a frame labelled "2" then it should be:
    on (release) {
        this._parent.gotoAndPlay("2");
    or other wise just the following to go to frame 2:
    on (release) {
         this._parent.gotoAndPlay(2);
    You just had a missing curly bracket...

  • ICloud backup is unable to access the account, because email I used for iCloud account is been deleted. And my iPad is stuck with this note on a screen, can't go Settings. How do I delete my account?

    iCloud backup is unable to access my account, because email I used for iCloud account is been deleted. And my iPad is stuck with this note on a screen, can't go Settings. How do I delete or edit my iCloud account?

    You can eirther I think go on ITunes or if you can get to settings you would just go to iCloud.

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • Can anybody help me to build an interface that can work with this code

    please help me to build an interface that can work with this code
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class Translate
    public static void main(String [] args) throws IOException
    if (args.length != 2)
    System.err.println("usage: Translate wordmapfile textfile");
    System.exit(1);
    try
    HashMap words = ReadHashMapFromFile(args[0]);
    System.out.println(ProcessFile(words, args[1]));
    catch (Exception e)
    e.printStackTrace();
    // static helper methods
    * Reads a file into a HashMap. The file should contain lines of the format
    * "key\tvalue\n"
    * @returns a hashmap of the given file
    @SuppressWarnings("unchecked")
    private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException
    BufferedReader in = null;
    HashMap map = null;
    try
    in = new BufferedReader(new FileReader(filename));
    String line;
    map = new HashMap();
    while ((line = in.readLine()) != null)
    String[] fields = line.split("
    t", 2);
    if (fields.length != 2) continue; //just ignore "invalid" lines
    map.put(fields[0], fields[1]);
    finally
    if(in!=null) in.close(); //may throw IOException
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
    * Process the given file
    * @returns String contains the whole file.
    private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException
    BufferedReader in = null;
    StringBuffer out = null;
    try
    in = new BufferedReader(new FileReader(filename));
    out = new StringBuffer();
    String line = null;
    while( (line=in.readLine()) != null )
    out.append(SearchAndReplaceWordsInText(words, line)+"\n");
    finally
    if(in!=null) in.close(); //may throw IOException
    return out.toString();
    * Replaces all occurrences in text of each key in words with it's value.
    * @returns String
    private static String SearchAndReplaceWordsInText(Map words, String text)
    Iterator it = words.keySet().iterator();
    while( it.hasNext() )
    String key = (String)it.next();
    text = text.replaceAll("\\b"key"
    b", (String)words.get(key));
    return text;
    * @returns: s with the first letter capitalized
    String capitalize(String s)
    return s.substring(0,0).toUpperCase() + s.substring(1);
    }... here's the head of my pirate_words_map.txt
    hello               ahoy
    hi                    yo-ho-ho
    pardon me       avast
    excuse me       arrr
    yes                 aye
    my                 me
    friend             me bucko
    sir                  matey
    madam           proud beauty
    miss comely    wench
    where             whar
    is                    be
    are                  be
    am                  be
    the                  th'
    you                 ye
    your                yer
    tell                be tellin'

    please help me i don t know how to go about this.my teacher ask me to build an interface that work with the code .
    Here is the interface i just build
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.awt.*;
    import javax.swing.*;
    public class boy extends JFrame
    JTextArea englishtxt;
    JLabel head,privatetxtwords;
    JButton translateengtoprivatewords;
    Container c1;
    public boy()
            super("HAKIMADE");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBackground(Color.white);
            setLocationRelativeTo(null);
            c1 = getContentPane();
             head = new JLabel(" English to private talk Translator");
             englishtxt = new JTextArea("Type your text here", 10,50);
             translateengtoprivatewords = new JButton("Translate");
             privatetxtwords = new JLabel();
            JPanel headlabel = new JPanel();
            headlabel.setLayout(new FlowLayout(FlowLayout.CENTER));
            headlabel.add(head);
            JPanel englishtxtpanel = new JPanel();
            englishtxtpanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
            englishtxtpanel.add(englishtxt);
             JPanel panel1 = new JPanel();
             panel1.setLayout(new BorderLayout());
             panel1.add(headlabel,BorderLayout.NORTH);
             panel1.add(englishtxtpanel,BorderLayout.CENTER);
            JPanel translateengtoprivatewordspanel = new JPanel();
            translateengtoprivatewordspanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
            translateengtoprivatewordspanel.add(translateengtoprivatewords);
             JPanel panel2 = new JPanel();
             panel2.setLayout(new BorderLayout());
             panel2.add(translateengtoprivatewordspanel,BorderLayout.NORTH);
             panel2.add(privatetxtwords,BorderLayout.CENTER);
             JPanel mainpanel = new JPanel();
             mainpanel.setLayout(new BorderLayout());
             mainpanel.add(panel1,BorderLayout.NORTH);
             mainpanel.add(panel2,BorderLayout.CENTER);
             c1.add(panel1, BorderLayout.NORTH);
             c1.add(panel2);
    public static void main(final String args[])
            boy  mp = new boy();
             mp.setVisible(true);
    }..............here is the code,please make this interface work with the code
    public class Translate
    public static void main(String [] args) throws IOException
    if (args.length != 2)
    System.err.println("usage: Translate wordmapfile textfile");
    System.exit(1);
    try
    HashMap words = ReadHashMapFromFile(args[0]);
    System.out.println(ProcessFile(words, args[1]));
    catch (Exception e)
    e.printStackTrace();
    // static helper methods
    * Reads a file into a HashMap. The file should contain lines of the format
    * "key\tvalue\n"
    * @returns a hashmap of the given file
    @SuppressWarnings("unchecked")
    private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException
    BufferedReader in = null;
    HashMap map = null;
    try
    in = new BufferedReader(new FileReader(filename));
    String line;
    map = new HashMap();
    while ((line = in.readLine()) != null)
    String[] fields = line.split("
    t", 2);
    if (fields.length != 2) continue; //just ignore "invalid" lines
    map.put(fields[0], fields[1]);
    finally
    if(in!=null) in.close(); //may throw IOException
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
    * Process the given file
    * @returns String contains the whole file.
    private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException
    BufferedReader in = null;
    StringBuffer out = null;
    try
    in = new BufferedReader(new FileReader(filename));
    out = new StringBuffer();
    String line = null;
    while( (line=in.readLine()) != null )
    out.append(SearchAndReplaceWordsInText(words, line)+"\n");
    finally
    if(in!=null) in.close(); //may throw IOException
    return out.toString();
    * Replaces all occurrences in text of each key in words with it's value.
    * @returns String
    private static String SearchAndReplaceWordsInText(Map words, String text)
    Iterator it = words.keySet().iterator();
    while( it.hasNext() )
    String key = (String)it.next();
    text = text.replaceAll("\\b"key"
    b", (String)words.get(key));
    return text;
    * @returns: s with the first letter capitalized
    String capitalize(String s)
    return s.substring(0,0).toUpperCase() + s.substring(1);
    }... here's the head of my pirate_words_map.txt
    hello               ahoy
    hi                    yo-ho-ho
    pardon me       avast
    excuse me       arrr
    yes                 aye
    my                 me
    friend             me bucko
    sir                  matey
    madam           proud beauty
    miss comely    wench
    where             whar
    is                    be
    are                  be
    am                  be
    the                  th'
    you                 ye
    your                yer
    tell                be tellin'

  • Can anybody help me with this code?

    I am a beginner to J2ME. The following is a small program I wrote just for test.
    Theoretically, in my opinion, I shall see in the screen a number increase from 1 to 29999 rapidly after execute the code. But instead, it displays nothing but only displays 29999 after several seconds . Can some body point out what's wrong with this code? Thanks.
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test extends MIDlet{
    int x=1;
    String b="";
    private Display display;
    public Test() {
    display = Display.getDisplay(this);
    public void startApp() {
    MyCanvas mc = new MyCanvas() ;
    display.setCurrent(mc) ;
    while(x<30000){
    b=String.valueOf(x);
    mc.repaint();
    x++;
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    class MyCanvas extends Canvas{
    public void paint(Graphics g){
    g.drawString(b,10,10,0);

    thanks, I have already got the answer. you are right, if repaint in a high speed the screen will show nothing. here is the code for it, thanks the expert of nokia forum.
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    //Counter
    //Need to know when a number has been painted and need to wait a for a fraction of a sec before
    //painting the next number. This wait also allows other events like "Exit" to be processed
    //Use double buffering to avoid flicker
    //Paint in a different thread to keep the UI responsive
    public class MyMIDlet extends MIDlet{
    int x=1;
    String b="";
    private Display display;
    Thread t = null;
    MyCanvas mc = null;
    public MyMIDlet() {
    display = Display.getDisplay(this);
    public void startApp() {
    mc = new MyCanvas();
    t = new Thread(mc) ;
    display.setCurrent(mc) ;
    b=String.valueOf(x);
    t.start();
    public void callbackPaintDone(){
    try{
    //provides the delay between every repaint and also time to react to Exit
    synchronized(this){
    wait(1);
    }catch(Exception e){}
    paintNextNumber();
    private void paintNextNumber(){
    if(x<30000){
    x++;
    b=String.valueOf(x);
    mc.doPaint = true; //signals that next number can be painted
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    class MyCanvas extends Canvas implements Runnable{
    Image buf = null;
    Graphics bg = null;
    public boolean doPaint = true;
    public MyCanvas(){
    buf = Image.createImage(getWidth(),getHeight());
    bg = buf.getGraphics();
    public void paint(Graphics g){
    bg.setColor(255,255,255);
    bg.fillRect(0,0,getWidth(),getHeight());
    bg.setColor(0);
    bg.drawString(b,10,10,0);
    g.drawImage(buf,10,10,Graphics.TOP|Graphics.LEFT);
    // Callback for next number to be painted
    MyMIDlet.this.callbackPaintDone();
    public void run(){
    while(true){
    if(doPaint){ //only paints when a number has been painted, and next one is ready to be painted
    doPaint = false;
    repaint();
    serviceRepaints();

  • Can somebody help me with this code?

    Can anyone help me with this code? My problem is that i can't
    seem to position this form, i want to be able to center it
    vertically & horizontally in a div either using CSS or any
    other means.
    <div id="searchbar"><!--Search Bar -->
    <div id="searchcart">
    <div class="serchcartcont">
    <form action='
    http://www.romancart.com/search.asp'
    name="engine" target=searchwin id="engine">
    <input type=hidden value=????? name=storeid>
    <input type=text value='' name=searchterm>
    <input type=submit value='Go'> </form>
    </div>
    </div>
    <div class="searchcont">Search For
    Products:</div>
    </div><!-- End Search Bar -->
    Pleasssssseeeeeeee Help
    Thanks

    Hi,
    Your form is defined in a div named "serchcartcont", you can
    use attributes like position and align of the div to do what you
    want to do. But there are two more dives above this dive, you will
    have define the height width of these before you can center align
    the inner most div. If you are not defining the height & width
    then by default it decide it automatically to just fit the content
    in it.
    Hope this helps.
    Maneet
    LeXolution IT Services
    Web Development
    Company

  • ASR Hyper-v (VMM) to Azure and we are stuck with this error while preparing the VMM Server

    We are stuck with this error while installing ASR provider and registering with Azure Vault, can i get some help on this
    Error:
    NO Vaults could be retried for the registration key. Please ensure that
    1, your registration key has not expired.You can re-downloading registration key from Azure site Recovery portal
    2, Your system clock is not out of sync with the selected system time zone
    System Clock is set to IST and Azure to southeastasia

    Hi,
    Could you please ensure that you have downloaded the latest registration key from the portal?
    Also ensure that the machine from where you are accessing the portal and the VMM server has the right time according to your time zone.
    Thank you,
    Ruturaj

  • Can somebody help me install IOS 6.1.3 back to my iPhone 4. IOS 7 is not smooth enough as perfect as IOS 6.1.3. I am stuck with this OS, every app gives a break for 4-5 seconds to open up. And playing games in this OS using iPhone 4 is really crazy

    Can somebody help me install IOS 6.1.3 back to my iPhone 4. IOS 7 or 7.0.4 is not smooth enough as perfect as IOS 6.1.3. I am stuck with this OS, every app gives a break for 4-5 seconds to open up. And playing games in this OS using iPhone 4 is really crazy. Very much disappointed that I am not able to use IOS 7 and cant go back to what I need.

    Mani Dinesh wrote:
    Can somebody help me install IOS 6.1.3 back to my iPhone 4.
    Downgrading is not supported by Apple.
    Mani Dinesh wrote:
    ...every app gives a break for 4-5 seconds to open up. ...
    See this discussion...
    https://discussions.apple.com/message/23731048#23731048

  • I have an emac running 10.5.8  I purchased snow leopard to upgrade. during the attempt to install, the computer says this is not an intel and is mot supported.  i think this is a power pc? am i stuck with this 10.5.8 version or is there away i can upgrade

    I have an emac running 10.5.8  I purchased a copy of snow leopard from apple. upon attempting the install i read that the computer is not an intel. I believe this is a power PC?  Is there a way to upgrade to the snow leopard or am I stuck with this version 10.5.8?  Thank you for any help.

    As Niel says, no way to go past 10.5.8 on your Mac, but there is a more upto date Browser...
    TenFourFox is the most up to date browser for our PPCs, they even have G4 & G5 optimized versions...
    http://www.floodgap.com/software/tenfourfox/

  • What's wrong with this content type definition?

    Could someone tell me what's wrong with this content type definition? When I click "New Folder" in a custom list, it should bring two fields 1) Name 2) Custom Order. However in my case when I click new folder, I see 1) Member (which is totally
    weird) 2) custom order. Where is it getting that Member field from?
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!-- Parent ContentType: Folder (0x0120) -->
    <ContentType ID="0x012000c0692689cafc4191b6283f72f2369cff"
    Name="Folder_OrderColumn"
    Group="Custom"
    Description="Folder with order column"
    Inherits="TRUE"
    Version="0">
    <FieldRefs>
    <FieldRef ID="{35788ED2-8569-48DC-B6DE-BA72A4F87B7A}" Name="Custom_x0020_Order" DisplayName="Custom Order" />
    </FieldRefs>
    </ContentType>
    </Elements>

    Hi,
    According to your post, my understanding is that you had an issue about the custom content type with custom column.
    I don’t think there is any issue in the content type definition, and it also worked well in my environment.
    Did you have the Member field in the project?
    I recommend you create a simple project only with one custom Order column and one custom Folder_OrderColumn, then you can add more fields one by one.
    By doing this, it will be easier to find out the root cause of this error.
    Thanks,
    Jason
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Jason Guo
    TechNet Community Support

  • Im stuck with this message "no bootable device, insert boot disk and press any key". Now i want to go back to mac os but everytime i turn on my laptop that message appear..kindly help... Please

    Im stuck with this message "no bootable device, insert boot disk and press any key". Now i want to go back to mac os but everytime i turn on my laptop that message appear..kindly help... Please .... Im using my usb as bootable device but it cant be detected..

    Reboot, hold the option key down, select OSX when the startup manager appears.

  • Please tell me what is the problem with this code

    Hai,
    Iam new to Swings. can any one tell what is the problem with this code. I cant see those controls on the frame. please give me the suggestions.
    I got the frame ,but the controls are not.
    this is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ex2 extends JFrame
    JButton b1;
    JLabel l1,l2;
    JPanel p1,p2;
    JTextField tf1;
    JPasswordField tf2;
    public ex2()
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setTitle("Another example");
    setSize(500,500);
    setVisible(true);
    b1=new JButton(" ok ");
    p1=new JPanel();
    p1.setLayout(new GridLayout(2,2));
    p2=new JPanel();
    p2.setLayout(new BorderLayout());
    l1=new JLabel("Name :");
    l2=new JLabel("Password:");
    tf1=new JTextField(15);
    tf2=new JPasswordField(15);
    Container con=getContentPane();
    con.add(p1);
    con.add(p2);
    public static void createAndShowGUI()
    ex2.setDefaultLookAndFeelDecorated(true);
    public static void main(String ar[])
    createAndShowGUI();
    new ex2();
    }

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ex2 extends JFrame
        JButton b1;
        JLabel l1,l2;
        JPanel p1,p2;
        JTextField tf1;
        JPasswordField tf2;
        public ex2()
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setTitle("Another example");
            b1=new JButton(" ok ");
            p1=new JPanel();
            p1.add(b1);
            p2=new JPanel();
            p2.setLayout(new GridLayout(2,2));
            l1=new JLabel("Name :");
            l2=new JLabel("Password:");
            tf1=new JTextField(15);
            tf2=new JPasswordField(15);
            p2.add(l1);
            p2.add(tf1);
            p2.add(l2);
            p2.add(tf2);
            Container con=getContentPane();
            con.add(p1, BorderLayout.NORTH);
            con.add(p2, BorderLayout.CENTER);
            pack();
            setVisible(true);
        public static void createAndShowGUI()
            ex2.setDefaultLookAndFeelDecorated(true);
        public static void main(String ar[])
            createAndShowGUI();
            new ex2();
    }

  • Vector, what is the problem with this code?

    Vector, what is the problem with this code?
    63  private java.util.Vector data=new Vector();
    64  Vector aaaaa=new Vector();
    65   data.addElement(aaaaa);
    74  aaaaa.addElement(new String("Mary"));on compiling this code, the error is
    TableDemo.java:65: <identifier> expected
                    data.addElement(aaaaa);
                                   ^
    TableDemo.java:74: <identifier> expected
                    aaaaa.addElement(new String("Mary"));
                                    ^
    TableDemo.java:65: package data does not exist
                    data.addElement(aaaaa);
                        ^
    TableDemo.java:74: package aaaaa does not exist
                    aaaaa.addElement(new String("Mary"));Friends i really got fed up with this code for more than half an hour.could anybody spot the problem?

    I can see many:
    1. i assume your code snip is inside a method. a local variable can not be declare private.
    2. if you didn't import java.util.* on top then you need to prefix package on All occurance of Vector.
    3. String in java are constant and has literal syntax. "Mary" is sufficient in most of the time, unless you purposly want to call new String("Mary") on purpose. Read java.lang.String javadoc.
    Here is a sample that would compile...:
    public class QuickMain {
         public static void main(String[] args) {
              java.util.Vector data=new java.util.Vector();
              java.util.Vector aaaaa=new java.util.Vector();
              data.addElement(aaaaa);
              aaaaa.addElement(new String("Mary"));
    }

Maybe you are looking for

  • Right/best method to open and close form?

    When i click a button from FormA, it open FormC and it should be the same with button from FormB-used to open the same FormC but it doesn't. this happen when i previously open FormC from FormA before opening it in FormB. I use setvisible(true) to ope

  • 2 different iphones have the same Apple ID, how can I change the apple ID on one of them but not delete the other iphone's data and media?

    2 different iphones have the same Apple ID, how can I change the apple ID on one of them but not delete the other iphone's data and media?

  • Download to Excel is hiding rows in a pivot view

    Hello , When downloading a report to excel from OBIEE Dashboard , certain rows are getting hidden . For instance , I have total 15 rows in my pivot view and when I download that report into excel format , the rows from 8-13 are not showing up . After

  • Sorting Music titel in store

    Did anybody now how it is possible to sort the music titels in the iTunes store? When I search a music titel I get a list of many titels of different artists. Now I tried to sort this list by artist or album or the length of titel. But it seems, that

  • Report Format q

    Hellow Gurus i have got one report in which Geting quanity on the basis of Billing Documents like Bill DOC A  in thich ZA is for preparation and YA for Cancellation of invoice B  ZB is for Prep and and YB is for Cancellation now in BW report m geting