Accessors/Mutators needed ???

I wrote a student grade calculation program. Now, our prof. gave us a sample program that tracks an employee and their salary and information. When I'm comparing mine to his, I notice I have no accessor/mutator (get/set) statements like he does. Am I doing something wrong? Am I missing something or should I be using the get/set commands anywhere? My program and output runs just fine. Thanks for the help. I am very new and this is my first time creating an object template.
Here is my StudentRecord program
// Title: ClassRecord.java
// Class: CSC-201 (Summer 2007)
// Assignment: HW #2
// Author: Me
// Last Modified:
// Description: A basic program that allows a user to enter information about
//              a student's grades to determine their overall numeric score for
//              the class as well as the final letter grade attained in the
//              course.
// Assumptions: - Students are identified by student ID #
//              - User is aware that tests are only 10 points each
//              - User is aware that midterm/Final exam are 100 points each
//              - User has to rerun the program to recalculate changes
// Deficiencies: - Does not check to see if students scored higher than the
//                 assumed maximum points for each assignment
//               - Limited to hard-coded number of quizzes/tests
//               - Limited to initial weights given for each quiz/test
//               - Does not use a students name
// CONSTRUCTORS
/* Default constructor */
/* Comprehensive constructor */
// MUTATOR METHODS
// ACCESSOR METHODS
// PUBLIC INTERFACE METHODS
// Precondition:
// Postcondition:
// PRIVATE HELPER METHODS
// Precondition:
// Postcondition:
// REQUIRED PACKAGES
import java.util.*;
public class StudentRecord {
//      INSTANCE VARIABLES
     private int studentID, quizOne, quizTwo, midTerm, finalExam, overallScore;
     private char letterGrade;
     public void readInput()
          Scanner keyboard = new Scanner(System.in);
          System.out.println("Please enter the Student's ID#: ");
          studentID = keyboard.nextInt();
          System.out.println("Please enter the score for Quiz 1: ");
          quizOne = keyboard.nextInt();
          System.out.println("Please enter the score for Quiz 2: ");
          quizTwo = keyboard.nextInt();
          System.out.println("Please enter the score for the Midterm: ");
          midTerm = keyboard.nextInt();
          System.out.println("Please enter the score for the Final Exam: ");
          finalExam = keyboard.nextInt();
     public void calculation()
          overallScore = (quizOne + quizTwo) * 5 / 4 + (midTerm / 4) +
                         finalExam / 2;
          if (overallScore >= 90)
               letterGrade =  'A';
          else if ((overallScore >= 80) && (overallScore < 90))
               letterGrade =  'B';
          else if ((overallScore >= 70) && (overallScore < 80))
               letterGrade =  'C';
          else if ((overallScore >= 60) && (overallScore < 70))
               letterGrade =  'D';
          else
               letterGrade =  'F';
     public void writeOutput()
          System.out.println("Student# " + studentID + " grade report");
          System.out.println("Quiz one = " + quizOne);
          System.out.println("Quiz two = " + quizTwo);
          System.out.println("Midterm = " + midTerm);
          System.out.println("Final = " + finalExam);
          System.out.println("Overall Score = " + overallScore);
          System.out.println("Final Letter Grade = " + letterGrade);
Here is the DriverStudentRecord that I use to test it.
public class DriverStudentRecord {
     public static void main(String[] args) {
    StudentRecord testStudent = new StudentRecord();
    testStudent.readInput();
    testStudent.calculation();
    testStudent.writeOutput();
Now here is a copy of my prof.'s program
// Title: Employee.java
// Class: CSC-201 (Fall 2006)
// Assignment: ICE #1
// Author: Ric Heishman
// Last Modified: 08/06/06
// Description: Template for an employee object.
// Assumptions: 1) employee number is a 5-digit integer.
//              2) salary cannot be negative.
//              3) first name limited to 10 characters.
//              4) last name limited to 15 characters.
// Deficiencies: None
// <-- text in file should be no wider than 80 characters so text doesn't wrap
//       when printed in portrait format -->
// REQUIRED PACKAGES
import java.text.NumberFormat;
import java.util.Locale;
public class Employee {
  // INSTANCE VARIABLES
  private int employeeNumber;   // class invariant: 5-digit limit
  private double salary;
  private String firstName,     // class invariant: 10 character limit
                 lastName,      // class invariant: 15 character limit
                 hireDate;
  // CONSTRUCTORS
  /* Default constructor */
  public Employee() {
    this(0,
         0.0,
         "firstname",
         "lastname",
         "hiredate");
  /* Comprehensive constructor */
  public Employee(int employeeNumber,
                  double salary,
                  String firstName,
                  String lastName,
                  String hireDate) {
    setEmployeeNumber(employeeNumber);
    setSalary(salary);
    setFirstName(firstName);
    setLastName(lastName);
    setHireDate(hireDate);
  // MUTATOR METHODS
  public void setEmployeeNumber(int employeeNumber) {
    if (employeeNumber >= 0 && employeeNumber <= 99999)
      this.employeeNumber = employeeNumber;
    else {
      System.out.println("Employee number must be between 0 -> 99999");
      System.exit(1);
  public void setSalary(double salary) {
    if (salary >= 0.0)
      this.salary = salary;
    else
      this.salary = 0.0;     // potential problem ???
  public void setFirstName(String firstName) {
    if (checkStringLength(firstName, 1))
      this.firstName = firstName;
    else {
      System.out.println("First Name must be < 10 characters");
      System.exit(1);
  public void setLastName(String lastName) {
    if (checkStringLength(lastName, 2))
      this.lastName = lastName;
    else {
      System.out.println("Last Name must be < 15 characters");
      System.exit(1);
  public void setHireDate(String hireDate) {
    this.hireDate = hireDate;
  // ACCESSOR METHODS
  public int getEmployeeNumber() {
    return employeeNumber;
  public double getSalary() {
    return salary;
  public String getFirstName() {
    return firstName;
  public String getLastName() {
    return lastName;
  public String getHireDate() {
    return hireDate;
  // PUBLIC INTERFACE METHODS
  // Precondition: requires Employee object to be compared to calling object
  // Postcondition: returns "true" if all fields of calling object and
  //                comparison object are identical
  public boolean equals(Employee employee) {
    if (this.employeeNumber == employee.employeeNumber &&
        this.firstName == employee.firstName &&
        this.lastName == employee.lastName &&
        this.hireDate == employee.hireDate &&
        this.salary == employee.salary)
      return true;
    else
      return false;
  // Precondition: Employee object has been instantiated
  // Postcondition: returns Sting representing current state of object
  public String toString() {
    return "Employee Number: " + employeeNumber + "\nEmployee Name: " +
         firstName + " " + lastName + "\nSalary: " + formatSalary(salary) +
           "\nHire Date: " + hireDate;
  // PRIVATE HELPER METHODS
  // Precondition: requires a string to be tested and an integer value
  //               representing a particular type of test for string length:
  //               (1) - maximum length of 10
  //               (2) - maximum length of 15
  // Postcondition: returns "true" if string length < particular maximum length
  private boolean checkStringLength(String string,
                                    int typeOfTest) {
    int maximumLength = 0;
    switch (typeOfTest) {
      case 1:
        maximumLength = 10;
        break;
      case 2:
        maximumLength = 15;
        break;
      default:
        System.out.println("Improper value for \"typeOfTest\" variable");
    if (string.length() < maximumLength)
      return true;
    else
      return false;
  // Precondition: requires double value to be formatted as US currency
  // Postcondition: returns String of input value formatted as US currency
  private String formatSalary(double salary) {
    Locale locale = Locale.US;
    return NumberFormat.getCurrencyInstance(locale).format(salary);
}

I wrote a student grade calculation program. Now, our prof. gave us a sample program that tracks an employee and their salary and information. When I'm comparing mine to his, I notice I have no accessor/mutator (get/set) statements like he does. Am I doing something wrong? Am I missing something or should I be using the get/set commands anywhere?
Well, how does he use his get/set? What do you do differently that you're getting the same results without using them?
There is this school of thought:
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html
While I think the author's presentation is a bit extreme, he does have some valid points.

Similar Messages

  • What accessories are needed to connect my Apple TV to my LCD projector (VGA connectors) in the classroom so that I can mirror my iPad for around the class teaching?

    I have been wanting to project my iPad to my class and the only way I have found is to use the connector. However, I would like to remove myself from in front of the classroom and move around the classroom. This encourages students to take notes and not pass notes. This also encourages them to engage in questioning of the lesson, because the teacher is not far removed from them if they're in the back of the classroom. How can I connect? I've read some forums that discuss converters and many who say it needs to be active or powered, but some of these powered converters are nearly two times the amount of the Apple TV. I wouldn't mind paying if this is the suggested way and it works. I don't want to go through several failed and expensive experiments.

    There are hardware converters that will convert HDMI to various other types of output, however there are some issues with doing so that you should be aware of.
    HDCP
    HDCP compliant converters will not allow you to watch HDCP protected content such as that from the iTunes Store. Non compliant converters exist but we cannot discuss them under the Terms of Use for these communities.
    Resolution and aspect ratio
    I'm not aware of any converters that will scale the output from the Apple TV, any TV or projector which is used will need to be widescreen and support resolutions of 720p (if you are using the Apple TV 2)

  • Need image to update with JComboBox selection

    hello, i have code here that loads an image from a JFileChooser dialog when "Add Image" is clicked, the images name and path is stored in a JComboBox, and the image name is displayed. As more images are added to the JComboBox, I would like to be able to have the picture displayed in concurrence with whatever image is selected from the comboBox. For instance, if Jessica.jpg is selected in the JComboBox, i need Jessica.jpg to be loaded into imagePanel. Here is the code. The problem lies within the JComboBox's "itemStateChanged" I believe... This is what must be used (i think) to update the pictures in the imagePanel when the combobox is manipulated....
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.border.*;
    import java.awt.image.BufferedImage;
    public class MyDialog extends JDialog implements ActionListener, WindowListener, ItemListener
         ReminderClass dataRec;
         ReminderClass originalDataRec;
         Image im;
         MediaTracker mt;
         Toolkit tk;
         JFileChooser imageDialog;
         File f;
         String[] comboBoxList;
         String fileName;
         String filePathName;
         DataManager dataManager;
         JPanel mainPanel1;
         JPanel mainPanel2;
         JPanel mainPanel3;
         JPanel buttonPanel;
         JPanel radioPanel;
         MyImageJPanel imagePanel;
         JScrollPane scrollPane1;
         JScrollPane scrollPane2;
         JRadioButton pendingButton;
         JRadioButton documentationButton;
         JRadioButton completedButton;
         JRadioButton failedButton;
         JRadioButton cancelledButton;
         ButtonGroup radioGroup;
         JComboBox imageComboBox;
         JComboBox category;
         JTextArea description;
         JTextArea message;
         JLabel descriptionLabel;
         JLabel messageLabel;
         JLabel fileNameLabel;
         JLabel categoryLabel;
         JLabel selectedFile;
         GregorianCalendar dueDateTime;
         GregorianCalendar reminderInterval;
         GregorianCalendar terminatedDateTime;
         JButton saveCont;
         JButton cancel;
         JButton addImage;
         JButton saveExit;
         JLabel dueDate;
         JLabel intervalDate;
         JLabel terminatedDate;
         JTextField dueDateField;
         JTextField intervalDateField;
         JTextField terminatedDateField;
         int choice;
         int newIndex;
         public MyDialog(DataManager aDataManager)
         {//add new Reminder to list d-box
              Container cp;
              dataManager = aDataManager;
              dataRec = new ReminderClass();
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              saveCont.setActionCommand("SAVECONT");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameAdd();
         public MyDialog(int index, DataManager aDataManager, ReminderClass newDataRec)
         {//edit an existing reminder dialog
              Container cp;
              dataManager = aDataManager;
              index = newIndex;
              dataRec = newDataRec;
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              dataRec.populateComboBox(imageComboBox);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              fillInData(dataRec);
              saveCont.setActionCommand("SAVECONT2");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT2");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL2");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameEdit();
         void setupMainFrameAdd()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Reminder Add New");
              setVisible(true);
         }//end of setupMainFrame
         void setupMainFrameEdit()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Edit Existing Reminder");
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              JOptionPane optionPane;
              String temp = new String();
              if (e.getActionCommand().equals("CANCEL"))
                   if(dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit without first saving data?","Are you sure you wish to\n" + "exit without first saving data?", JOptionPane.YES_NO_OPTION);
                        if(choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             for (int n = 0; n<imageComboBox.getItemCount(); n++)
                                  dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                             dataRec.setCategory(category.getSelectedIndex());
                             dataManager.add(dataRec);
                             fillInData(dataRec);
                             dispose();
                   else
                        dispose();
              else if (e.getActionCommand().equals("CANCEL2"))
                   if (dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to\n" + "exit without first saving data?");
                        if (choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             this.dispose();
              else if (e.getActionCommand().equals("ADDIMAGE"))
                   filePathName = new String();
                   fileName = new String();
                   imageDialog = new JFileChooser();
                   imageDialog.showOpenDialog(this);
                   f = imageDialog.getSelectedFile();
                   tk = Toolkit.getDefaultToolkit();
                   fileName = f.getName();
                   filePathName = f.getPath();
                   im = tk.getImage(filePathName);
                   try
                        mt = new MediaTracker(this);
                        mt.addImage(im, 432);
                        mt.waitForAll();
                   catch(InterruptedException ie)
                        ie.getStackTrace();
                   imageComboBox.addItem(fileName);
                   dataRec.setImageFileName(fileName);
                   imageComboBox.setSelectedItem(fileName);
                   imagePanel.refreshImage(im , 50, 50);
              else if (e.getActionCommand().equals("SAVECONT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   temp = dueDateField.getText();
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add((ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);     
              else if (e.getActionCommand().equals("SAVECONT2"))
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex,(ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);
              else if (e.getActionCommand().equals("SAVEEXIT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add(dataRec);
                   fillInData(dataRec);
                   dispose();
                   //save new data to list, and exit back to main prog.
              else if (e.getActionCommand().equals("SAVEEXIT2"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex, (ReminderClass)(dataRec.clone()));
                   fillInData(dataRec);
                   dispose();
              else if (e.getActionCommand().equals("PENDING"))
                   dataRec.setStatus("Pending");
              else if (e.getActionCommand().equals("DOCUMENTATION"))
                   dataRec.setStatus("Documentation");
              else if (e.getActionCommand().equals("COMPLETED"))
                   dataRec.setStatus("Completed");
              else if (e.getActionCommand().equals("FAILED"))
                   dataRec.setStatus("Failed");
              else if (e.getActionCommand().equals("CANCELLED"))
                   dataRec.setStatus("Cancelled");
         public void itemStateChanged(ItemEvent e)
               JComboBox cb = (JComboBox)e.getSource();
               int categorySelection;
               if(cb == category)
                 categorySelection = cb.getSelectedIndex();
               if (cb == imageComboBox)
                       tk = Toolkit.getDefaultToolkit();
                        fileName = dataRec.getImageFileName();
                        filePathName = f.getPath();
                        im = tk.getImage(filePathName);
                        try
                             mt = new MediaTracker(this);
                             mt.waitForAll();
                             mt.addImage(im, 432);
                             imagePanel.refreshImage(im , 50, 50);
                        catch(InterruptedException ie)
                        ie.getStackTrace();
         public void fillInData(ReminderClass d)
              fileNameLabel.setText(d.getImageFileName());
              description.setText(d.getDescription());
              message.setText(d.getMessage());
              category.setSelectedIndex(d.getCategory());
         public void windowOpened(WindowEvent e)
              //no action to take
         public void windowClosing(WindowEvent e)
              JOptionPane j = new JOptionPane("Are you sure you wish to exit \n" + "without saving data first?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);;
         public void windowClosed(WindowEvent e)
    //          no action to take
         public void windowIconified(WindowEvent e)
    //          no action to take
         public void windowDeiconified(WindowEvent e)
    //          no action to take
         public void windowActivated(WindowEvent e)
    //          no action to take
         public void windowDeactivated(WindowEvent e)
    //          no action to take
    }Here is the main "ReminderClass" with all methods and accessors/mutators....
    import java.util.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    //search for Java Thumb Wheel under Google.
    public class ReminderClass extends Object implements Cloneable, Comparable
          private int category;
          private String description;
          private String message;
          private GregorianCalendar dueDateTime;
         private GregorianCalendar reminderInterval;
          private GregorianCalendar terminatedDateTime;
          private int displayStyle;
          private int compareKey;
          private String status;
          String[] imagePathArray;
          String[] imageArray;
          String imageFileName;
          int numImages;
          public final static int CATEGORY_FIELD = 1;
          public final static int DESCRIPTION_FIELD = 2;
          public final static int MESSAGE_FIELD = 3;
          public final static int DUE_DATE_TIME_FIELD = 4;
          public final static int REMINDER_INTERVAL_FIELD =5;
          public final static int TERMINATED_DATE_TIME_FIELD = 6;
          public final static int DISPLAY_STYLE_FIELD = 7;
          public final static int COMPARE_KEY_FIELD = 8;
          public final static int STATUS_FIELD = 9;
          static boolean showDescription = false;
          static boolean showDate = false;
          static boolean showCategory = false;
          static boolean showMessage = false;
          static boolean showDueDateTime = false;
          static boolean showReminderInterval = false;
          static boolean showTerminatedDateTime = false;
          static boolean showImageName = false;
          static boolean showStatus = false;
          //******************REMINDER CLASS DEFAULT CONSTRUCTOR***************
          ReminderClass()
               numImages = 0;
               imageArray = new String[20];
               imagePathArray = new String[20];
               imageFileName = "";
               category = -1;
               description = "";
               message = "";
               dueDateTime = new GregorianCalendar();
               reminderInterval = new GregorianCalendar();
               terminatedDateTime = new GregorianCalendar();
               displayStyle = -1;
               compareKey = -1;
         //     *****************REMINDER CLASS INITIALIZER CONSTRUCTOR*************
          ReminderClass(int initCategory, String initDescription, GregorianCalendar initDueDateTime, String[] initImagePathArray, String[] initImageArray, String initImageFileName,
                    GregorianCalendar initReminderInterval, GregorianCalendar initTerminatedDateTime, String initMessage, String initStatus,
                     int initCompareKey, int initDisplayStyle)
               imagePathArray = new String[20];
               imageArray = new String[20];
               for (int n = 0; n<initImageArray.length; n++)
                    imageArray[n] = initImageArray[n];
               for (int n = 0; n<initImagePathArray.length; n++)
                    imagePathArray[n] = initImagePathArray[n];
                    imageFileName = initImageFileName;
                     category = initCategory;
                     description = initDescription;
                     dueDateTime = (GregorianCalendar)initDueDateTime.clone();
                     reminderInterval = (GregorianCalendar)initReminderInterval.clone();
                     terminatedDateTime = (GregorianCalendar)initTerminatedDateTime.clone();
                     message = initMessage;
                     status = initStatus;
                     compareKey = initCompareKey;
                     displayStyle = initDisplayStyle;
               //*********************LOAD DATA FROM FILE WITH CONSTRUCTOR*****************************
            public ReminderClass(DataInputStream dataInStream) throws IOException
                           imageFileName = dataInStream.readUTF();
                       category = dataInStream.readInt();
                       description = dataInStream.readUTF();
                       message = dataInStream.readUTF();
                       dueDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       reminderInterval = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt()); 
                       terminatedDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       displayStyle = dataInStream.readInt();
                       compareKey = dataInStream.readInt();
                       status = dataInStream.readUTF();
             //********************SAVE DATA TO FILE***************************
             public void write(DataOutputStream dataOutStream) throws IOException
                       dataOutStream.writeUTF(imageFileName);
                       dataOutStream.writeInt(category);
                       dataOutStream.writeUTF(description);
                       dataOutStream.writeUTF(message);
                       dataOutStream.writeInt(dueDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.SECOND));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.YEAR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.HOUR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MINUTE));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.SECOND));         
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.SECOND));        
                       dataOutStream.writeInt(displayStyle);
                       dataOutStream.writeInt(compareKey);
                       //dataOutStream.writeUTF(status);
             public void clearFields()
                   numImages = 0;
                   imageFileName = "";
                   category = -1;
                    description = "";
                    message = "";
                    dueDateTime = new GregorianCalendar();
                    reminderInterval = new GregorianCalendar();
                    terminatedDateTime = new GregorianCalendar();
                    displayStyle = -1;
                    status = "";
                    compareKey = -1;
               //************* OVERRIDE clone METHOD***********************
               public Object clone() 
                         ReminderClass c = new ReminderClass();
                         try
                              c = ((ReminderClass)super.clone());
                              c.setImageArray(imageArray);
                              c.setImagePathArray(imagePathArray);
                              c.imageFileName = (String)imageFileName;
                              c.category = (int)category;
                              c.description = (String)description;
                              c.message = (String)message;
                              c.status = (String)status;
                              c.compareKey = (int)compareKey;
                              c.displayStyle = (int)displayStyle;
                              c.dueDateTime = (GregorianCalendar)(dueDateTime.clone());
                              c.reminderInterval = (GregorianCalendar)(reminderInterval.clone());
                              c.terminatedDateTime = (GregorianCalendar)(terminatedDateTime.clone());
                         catch (CloneNotSupportedException e)
                              System.out.println("Fatal Error: " + e.getMessage());
                              System.exit(1);
                         return c;
          //**************** OVERRIDE toString METHOD*************************
          public String toString()
               String s = new String();
               s =  description;
              if (showCategory)
                    s = s + "," + CategoryConversion.categories[category];
              if (showImageName)
                   s = s + "," + "'" + imageFileName + "'";
              if (showMessage)
                    s = s + "," + message;
              if (showStatus)
                   s = s + "," + status;
              if (showDueDateTime)
                    s = s + ", " + dueDateTime.get(Calendar.MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.YEAR);
                    s = s + "  " + dueDateTime.get(Calendar.HOUR);
                    s = s + ":" + dueDateTime.get(Calendar.MINUTE);
                    s = s + ":" + dueDateTime.get(Calendar.SECOND);
              if (showReminderInterval)
                    s = s + ", " + reminderInterval.get(Calendar.MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.YEAR);
                    s = s + "  " + reminderInterval.get(Calendar.HOUR);
                    s = s + ":" + reminderInterval.get(Calendar.MINUTE);
                    s = s + ":" + reminderInterval.get(Calendar.SECOND);
              if (showTerminatedDateTime)
                    s = s + ", " + terminatedDateTime.get(Calendar.MONTH);
                    s = s + "/" + terminatedDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" +terminatedDateTime.get(Calendar.YEAR);
                    s = s + "  " + terminatedDateTime.get(Calendar.HOUR);
                    s = s + ":" + terminatedDateTime.get(Calendar.MINUTE);
                    s = s + ":" + terminatedDateTime.get(Calendar.SECOND);
               return s;
          //******************COMPARE TO OBJECT*********************************
          public int compareTo(Object r)
               ReminderClass x;
               x = (ReminderClass)r;
               if (
                   (x.getCategory() == this.category)
               && (x.getDescription().equals(this.description))
               && (x.getMessage().equals(this.message))
               && (x.getImageFileName().equals(this.imageFileName))
               && (x.getDueDateTime().equals(this.dueDateTime))
               && (x.getReminderInterval().equals(this.reminderInterval))
               && (x.getTerminatedDateTime().equals(this.terminatedDateTime))
              return 0;
               else     
              return 1;
          //*************** ACCESSORS AND MUTATORS INCLUDING DISPLAY STYLE*******
          public void setDisplayStyle(int newDisplayStyle)
               displayStyle = newDisplayStyle;
          public int getDisplayStyle()
               return displayStyle;
          public int getCompareKey()
               return compareKey;
          public void setCompareKey(int newCompareKey)
               compareKey = newCompareKey;
          public int getCategory()
               return category;
          public void setImageFileName(String newFileName)
               imageFileName = newFileName;
          public String getImageFileName()
               return imageFileName;
          public void setCategory(int newCategory)
               category = newCategory;
          public String getDescription()
               return description;
          public void setDescription(String newDescription)
               description = newDescription;
          public void setImageArray(String[] array)
               imageArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imageArray[n] = array[n];
          public void setImagePathArray(String[] array)
               imagePathArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imagePathArray[n] = array[n];
          public String getImagePathArray(int index)
               return imagePathArray[index];
          public void populateComboBox(JComboBox jcb)
               for (int n = 0; n<numImages; n++)
                     jcb.addItem(imageArray[n]);
          public void addImageToArray(String s)
               imageArray[numImages] = s;
               numImages++;
          public String getMessage()
               return message;
          public void setMessage(String newMessage)
               message = newMessage;     
          public GregorianCalendar getDueDateTime()
               return dueDateTime;
          public void setDueDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                    int newSecs)
              dueDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);           
          public GregorianCalendar getReminderInterval()
               return reminderInterval;
          public void setReminderInterval(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
               reminderInterval = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);
          public GregorianCalendar getTerminatedDateTime()
               return terminatedDateTime;
          public void setTerminatedDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
              terminatedDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);      
          public String getStatus()
               return status;
          public void setStatus(String selection)
               status = selection;
          static public void setShowDate(boolean state)
               showDate = state;
          static public boolean getShowDate()
               return showDate;
          static public void setShowCategory(boolean state)
               showCategory = state;
          static public boolean getShowCategory()
               return showCategory;
          static public void setShowImageName(boolean state)
               showImageName = state;
          stat                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

    You don't really expect us to read through 300 lines of code do you?
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    In the meantime I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html]How to Use Combo Boxes for a working example that does exactly what you want.

  • My first java programming - Need some help please!!!

    I have to create a simple java program which i am not good at i am ok in C but my java is quite bad. The program need to define a class called Student and with a string called StudentNAme, a integer StudentID(key), An array of 8 integers called Marks that holds the students marks for 8 modules. It also says Include appropriate accessors, mutators and constructor(s) as well as a method to update the student�s marks. Anybody please help me in this question. I prefer an simple example of this program so I can learn faster, I dont even know how to declare a class.. So sorry but please help me out and thanks in advance

    I would also suggest you try using an IDE like
    eclipse (free)
    www.eclipse.org
    This will help you get a working program much faster.But please do also tell them that if they have troubles using it, they're supposed to read the IDE manual instead of posting here.

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belief.
    But in Java, it's easy enough to declare an instance variable public thus eliminating the need to write accessor method. What's the rational behind this feature? Is it merely to save developer some time from typing in the accessor methods? Does this reason justify the use of public members?

    I know some OOP purists believe all instance variables
    should be private, ALL? No way!
    and if there's a need to view or
    set the value of these instance variable, public
    accessor methods need to be created. There has to be a reason for any :- public int getMyInt(){ ...
    and in many cases protected or default package is more appropriate
    Data
    encapsulation is the driving force behind this belief.
    Correct , also avoiding multiple instances of member states - very often its a control issue too
    But in Java, it's easy enough to declare an instance
    variable public Yes and its also easy enough to write shittie code too ...
    if an instance variable is public there should be a clear comment explaining why the field has to be public
    thus eliminating the need to write
    accessor method. There's nothing wrong with accessors and mutators - the java language is full if them
    What's the rational behind this
    feature? As you stated encapsulation
    Is it merely to save developer some time
    from typing in the accessor methods? This is a lame reason
    Does this reason
    justify the use of public members?and attract unwanted side effects?
    I also don't like to see (or to write) a huge long list of getters and setters at the bottom of any class file and find it quite ugly - You should use them when you need to, not as a matter of routine.
    Accessor - mutator is a design issue for private instance variables that you wish to keep hidden. Your suggestion to make them all public is also a design issue and if I was to see a long list of public variables at the beginning of a class (unexplained with javadoc comments) I would be very puzzled indeed.
    Eclipse will automate the generation of accessors and mutators for you and also has a refactoring tool too - both are extremely useful

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • PXI 2532, TB 2641 - Need information on interface board solutions

    Hi.  I'm working on a project where I am going to be using a PXI-2532 and a TB-2641 to set up an 8 x 64 switch matrix.  I need an possible solutions for an interface board that will take the signals from the  3 ribbon cables from the TB-2641 and route them to either terminal blocks or some connector that I can then wire my measurment signals into. I was hoping to use a 90 pin femal Elco connector, but right now will look at any options.  Please let me know of any interface board solutions that are out there for me to look at.
    Thanks,
    Doug

    No problem Doug,
    The SCB-264x is just listed as an accessory right underneath all of the terminal blocks and with the cable options.  If you contact an NI sales representative when trying to configure a system, they will be able to help you pick all of the correct accessories you need.
    I will also recommend you check out our tutorial How to Connect Signals to the PXI/PXIe-2532 that walks through all of the components you'll have and the steps necessary to connect them in your system.
    Eric S.
    AE Specialist | Global Support
    National Instruments

  • If i replace my iphone5. will i get a new iphone5 with box and all new accessories?

    if i replace my iphone5. will i get a new iphone5 with box and all new accessories?

    Vague.
    If you buy a new on , then yes you will get all of that.
    If it is replaced under warranty, then no.  You will get a service unit, could be a refurb, with no accessories - you need to keep everything but the iphone itself when you have it exchanged.

  • Challange for you, help for me! java program

    I am a beginning java student and desparately (again) in help of someone who will check my java program. See below what they want from me, and try to make a program of it that works in all the ways that are asked. Thank you for helping me, i am running out of time.
    Prem Pradeep
    [email protected]
    Catalogue Manager II
    Specification:
    1.     Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    2.     Data input will come from a text file, whose name is passed in as the first command-line argument to the program. This data file may include up to 30 data items (the program will need to be able to support a variable number of actual items in the array without any errors).
    3.     The data lines will be in the format: CatNo:Description:Price Use a StringTokenizer object to separate these data lines into their components.
    4.     A menu should appear, prompting the user for an action:
    a.     Display all goods: this will display a summary (in tabulated form) of all goods currently stored in the catalogue: per item the category, description, price excluding tax, payable tax and price including tax.
    b.     Dispfay cheapest/dearest goods: this will display a summary of all the cheapest and most expensive item(s) in the catalogue. In the case of more than one item being the cheapest (or most expensive), they should all be listed.
    c.     Sort the list: this will use a selection sort algorithm to sort the list in ascending order, using the catalogue number as the key.
    d.     Search the list: this will prompt the user for a catalogue number, and use a binary search to find the data. If the data has not yet been sorted, this menu option should not operate, and instead display a message to the user to sort the data before attempting a search
    5.     Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    6.     Use modifiers where appropriate to:
    a.     Ensure that data is properly protected;
    b.     Ensure that the accessors and mutators are most visible;
    c.     The accessors and mutators for the catalogue number and description cannot be overridden.
    d.     The constant for the tax rate is publicly accessible, and does not need an instance of the class present in order to be accessible.
    7.     The program should handle all exceptions wherever they may occur (i.e. file 1/0 problems, number formatting issues, etc.) A correct and comprehensive exception handling strategy (leading to a completely robust program) will be necessary and not an incomplete strategy (i.e. handling incorrect data formats, but not critical errors),
    Sample Execution
    C:\> java AssignmentSix mydata.txt
    Loading file data from mydata.txt ...17 item(s) OK
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    The goods cannot be searched, as the list is not yet sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: b
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    BA023      Headphones      23.00      3.45      26.45
    JW289      Tape Recorder     23.00      3.45      26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    ZZ338      Wristwatch      295.00 44.25      339.25
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: c
    The data is now sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    Enter the catalogue number to find: ZJ282
    Cat Description ExTax Tax IncTax
    ZJ282 Pine Table 98.00 14.70 112.70
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: e
    Here you have the program as far as I could get. Please try to help me make it compact and implement a sorting method.
    Prem.
    By the way: you can get 8 Duke dollars (I have this topic also in the beginnersforum)
    //CatalogueManager.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueManager {
    // private static final double TAXABLE_PERCENTAGE = 0.15;
    // Require it to be publicly accessible
    // static means it is class variable, not an object instance variable.
    public static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueManager */
    public CatalogueManager() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueManager(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setCatalogNumnber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setDescription(String pDescription) {
    description = pDescription;
    // the accessors must be most visible
    // the final keyword prevents overridden
    public final String getDescription() {
    String str = description;
    return str;
    // If the parameter is not a double type, set the price = 0;
    // the mutators must be most visible
    public boolean setPrice(String pPrice) {
    try {
    price = Double.parseDouble(pPrice);
    return true;
    catch (NumberFormatException nfe) {
    price = 0;
    return false;
    // the accessors must be most visible
    public double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_ALLOW = 30;
    int MAX_CURRENT_INPUT = 0;
    FileReader fr;
    BufferedReader br;
    CatalogueManager[] catalogList = new CatalogueManager[MAX_INPUT_ALLOW];
    String str;
    char chr;
    boolean bolSort = false;
    double cheapest = 0;
    double mostExpensive = 0;
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    if (args.length != 1) {
    System.out.println("The application expects one parameter only.");
    System.exit(0);
    try {
    fr = new FileReader(args[0]);
    br = new BufferedReader(fr);
    int i = 0;
    while ((str = br.readLine()) != null) {
    catalogList[i] = new CatalogueManager();
    StringTokenizer tokenizer = new StringTokenizer(str, ":" );
    catalogList.setCatalogNumnber(tokenizer.nextToken().trim());
    catalogList[i].setDescription(tokenizer.nextToken().trim());
    if (! catalogList[i].setPrice(tokenizer.nextToken())){
    System.out.println("The price column cannot be formatted as dobule type");
    System.out.println("Application will convert the price to 0.00 and continue with the rest of the line");
    System.out.println("Please check line " + i);
    if (catalogList[i].getPrice() < cheapest) {
    cheapest = catalogList[i].getPrice();
    if (catalogList[i].getPrice() > mostExpensive) {
    mostExpensive = catalogList[i].getPrice();
    i++;
    fr.close();
    MAX_CURRENT_INPUT = i;
    catch (FileNotFoundException fnfe) {
    System.out.println("Input file cannot be located, please make sure the file exists!");
    System.exit(0);
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    System.out.println("Application cannot read the data from the file!");
    System.exit(0);
    boolean bolLoop = true;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    do {
    System.out.println("");
    System.out.println("CATALOGUE MANAGER: MAIN MENU");
    System.out.println("============================");
    System.out.println("a) display all goods b) display cheapest/dearest goods");
    System.out.println("c) sort the goods list d) search the good list");
    System.out.println("e) quit");
    System.out.print("Option:");
    try {
    str = stdin.readLine();
    if (str.length() == 1){
    str.toLowerCase();
    chr = str.charAt(0);
    switch (chr){
    case 'a':
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'b':
    System.out.println("");
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == cheapest){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    System.out.println("MOST EXPENSIVE GODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == mostExpensive) {
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'c':
    if (bolSort == true){
    System.out.println("The data has already been sorted");
    else {
    System.out.println("The data is not sorted");
    break;
    case 'd':
    break;
    case 'e':
    bolLoop = false;
    break;
    default:
    System.out.println("Invalid choice, please re-enter");
    break;
    catch (IOException ioe) {
    System.out.println("ERROR:" + ioe.getMessage());
    System.out.println("Application exits now");
    System.exit(0);
    } while (bolLoop);

    One thing you're missing totally is CatalogueItem!! A CatalogueManager manages the CatalogueItem's, and is not an CatalogueItem itself. So at least you have to have this one more class CatalogueItem.
    public class CatalogueItem {
    private String catalogNumber;
    private String description;
    private double price;
    //with all proper getters, setters.
    Then CatalogueManager has a member variable:
    CatalogueItem[] items;
    Get this straight and other things are pretty obvious...

  • URGENT Check this code for me please

    Dear whoeverthisreads, please read and see at the bottom my sourcecode, or whatever I could make of it until (even with help) I failed to see any solution. Please copy, paste and run to see if you can manage to adjust the program to make it work in the way as described. And I think I made it unnecessarily complicated. Whatever you can do for me, I will be very, very grateful.
    Prem Pradeep, email: [email protected]
    (A beginning dutch Java student who is running out of time and hope)
    Catalogue Manager
    Specification:
    a) Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    b) Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    c) Use an array of 5 CatalogueItem items to store data. (You may assume that no imported goods will be recorded.)
    d) Write a driver program that prompts for three sets of user input (catalogue number, description and price), to be stored in the atalogueItem instance.
    e) The data are to be read for each item in a single line. The data lines will be in the format:
    CatNo:Description:Price
    Use a StringTokenizer object to separate these data lines into their components.
    f) Review the class definition of CatalogueItem, and use modifiers where appropriate to:
    � Ensure that data is properly protected;
    � Ensure that the accessors and mutators are most visible;
    � The accessors and mutators for the catalogue number and description cannot be overridden.
    � The constant for the tax rate is publicly accessible, and does not need an instance of the class
    present in order to be accessible.
    As well as a summary, the program should also calculate and display:
    � All of the cheapest and most expensive item(s) in the catalogue. In the case of more than one
    item being the cheapest (or most expensive), they should all be listed.
    � A total of the pre-tax worth of the goods in the catalogue.
    � The average amount of tax on the items in the catalogue.
    A sample execution of the program may be as follows (output should be tabulated):
    Enter five items of data:
    AA123: Telephone: 52.00
    ZJ282: Pine Table: 98.00
    BA023: Headphones: 23.00
    ZZ338: Wristwatch: 295.00
    JW289: Tape Recorder: 23.00
    LISTING OF ALL GOODS
    Cat      Description      ExTax           Tax           IncTax ~
    ZJ282      pine Table           98.00           14.70           112.70
    AA123 Telephone           52.00           7.80           59.80
    BA023 Headphones      23.00           3.45           26.45
    ZZ338      Wristwatch      295.00      44.25      339.25
    JW289 Tape Recorder      23.00           3.45           26.45
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax           Tax           IncTax
    BA023 Headphones           23.00           3.45           26.45
    JW289 Tape Recorder      23.00           3.45           26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax           Tax           IncTax
    ZZ338      Wristwatch      295.00      44.25      339.25
    TOTAL PRE-TAX WORTH OF CATALOGUE ITEMS:      491.00
    AVERAGE AMOUNT OF TAX PAYABLE PER ITEM:      14.73
    The next code is what I could make of it�until I got terribly stuck...
    //CatalogueItem.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueItem {
    private static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueItem */
    public CatalogueItem() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueItem(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    void setCatalogNumber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    void setDescription(String pDescription) {
    description = pDescription;
    String getDescription() {
    String str = description;
    return str;
    void setPrice(String pPrice) {
    price = Double.parseDouble(pPrice);
    double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    // System.out.println("String is " + str1);
    // System.out.println("The format value : " + value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_SET = 5;
    final String strQ = "Enter five items of data:";
    CatalogueItem[] catalogList = new CatalogueItem[MAX_INPUT_SET];
    String strInput;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    // Input of five items with three data each, delimiter ":"
    for (int i = 0; i < MAX_INPUT_SET; i++) {
    catalogList[i] = new CatalogueItem();
    System.out.print(strQ);
    strInput = stdin.readLine();
    StringTokenizer tokenizer = new StringTokenizer(strInput, ":" );
    String inCatNo = tokenizer.nextToken();
    String inDescr = tokenizer.nextToken();
    String inPrice = tokenizer.nextToken();
    catalogList.setCatalogNumnber(inCatNo);
    catalogList[i].setDescription(inDescr);
    catalogList[i].setPrice(inPrice);
    // Listing of all goods
    System.out.println("LISTING OF ALL GOODS");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_INPUT_SET; i++) {
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    // This should pick the cheapest and most expensive goods in catalogue, but
    // this code is not good:
    // In the case of more than one item being the cheapest (or most expensive),
    // they should all be listed.
    double cheapest = cataloguelist[1].getPrice();
    double mostExpensive = cataloguelist[1].getPrice();
              for(int i=2; i< MAX_INPUT_SET; i++){
                   if (cataloguelist[i].getPrice < cheapest)
              cheapest = i;}
              for(int i=2; i< MAX_INPUT_SET; i++){
                   if (cataloguelist[i].getPrice > mostExpensivet)
              mostExpensive = i;}
    // Lists cheapest goods (not complete enough)
    i = cheapest;
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    // Lists most expensive goods (not complete enough)
    i = mostExpensive;
    System.out.println("MOST EXPENSIVE GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());}}
    // Generates and shows total pre-tax worth of catalogue items (how??)
    // generates and shows amount of tax payable per item (how??)

    How is this:
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class Cat
         Vector items = new Vector();
    public Cat()
    public void read(String fname)
         FileReader     fr;
        BufferedReader br;
         String         str ="";
        try
             fr = new FileReader(fname);
            br = new BufferedReader(fr);
            while ((str = br.readLine()) != null && items.size() < 30)
                   if (!str.trim().equals(""))
                        StringTokenizer tokenizer = new StringTokenizer(str, ":");
                     String n = tokenizer.nextToken().trim();
                        String d = tokenizer.nextToken().trim();
                        String s = tokenizer.nextToken().trim();
                        double p = Double.parseDouble(s);
                        items.add(new Item(n,d,p));
            fr.close();
        catch (FileNotFoundException e)
            System.out.println("Input file cannot be located, please make sure the file exists!");
            System.exit(0);
        catch (IOException e)
            System.out.println(e.getMessage());
            System.out.println("Application cannot read the data from the file!");
            System.exit(0);
    public void displayAll()
         for (int j=0; j < items.size(); j++)
              Item item = (Item)items.get(j);
              System.out.println(item.toString());
    public void sort()
         Collections.sort(items);     
    public class Item implements Comparable
         String       number, description;
         double       price,pricep;
         final double TAXRATE = 0.15;
    public Item(String number, String description, double price)
         this.number      = number;
         this.description = description;
         this.price       = price;
         this.pricep      = price * TAXRATE;
    public int compareTo(Object o1)
         String o = ((Item)o1).number;
         return(number.compareTo(o));
    public String toString()
         DecimalFormat df = new DecimalFormat("#.00");     
         String        p1 = df.format(TAXRATE*price);
         String        p2 = df.format(TAXRATE*price+price);
         String s = number+"\t "+description+"\t"+price+"\t"+p1+"\t"+p2+"\t" ;
         return(s);
    public static void main (String[] args)
         Cat catalog = new Cat();
         catalog.read("C31.dat");
         String reply = "";
         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
         while (!reply.equals("e"))
              System.out.println("");
            System.out.println("CATALOGUE MANAGER: MAIN MENU");
            System.out.println("============================");
            System.out.println("a) display all goods        b) display cheapest/dearest goods");
            System.out.println("c) sort the goods list      d) search the good list");
            System.out.println("e) quit");
            System.out.print("Option:");
              try
                   reply = stdin.readLine();
              catch (IOException e)
                System.out.println("ERROR:" + e.getMessage());
                System.out.println("Application exits now");
                System.exit(0);
              if (reply.equals("a")) catalog.displayAll();
              if (reply.equals("c")) catalog.sort();
    Noah

  • JSF newbie question - ServletException - Method not found

    I just started learning JSF (and JSP) by following the tutorial:
    JSF for nonbelievers: Clearing the FUD about JSF
    http://www-128.ibm.com/developerworks/library/j-jsf1/
    I'm getting a ServletException and I'm not sure why. Instead of starting the tutorial over, I'd like to learn what I'm doing wrong.
    The exception is:
    exception
    javax.servlet.ServletException: Method not found: [email protected]()
    root cause
    javax.el.MethodNotFoundException: Method not found: [email protected]()In the calculator.jsp page (a simple page with two form fields), I noticed that when I type CalcBean., my IDE (NetBeans) only autocompletes the class variables and neither of the methods (add and multiply). I quickly searched and someone suggested restarting the server. This did not fix my problem. I must be doing something completely wrong or I missed something in the tutorial. If you don't mind, please read the simple files below and see if you can spot anything wrong. Please keep in mind this is my first time using JSF (and JSP for that matter). If you can suggest a better newbie tutorial, please do! Thanks
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <context-param>
            <param-name>com.sun.faces.verifyObjects</param-name>
            <param-value>false</param-value>
        </context-param>
        <context-param>
            <param-name>com.sun.faces.validateXml</param-name>
            <param-value>true</param-value>
        </context-param>
        <context-param>
            <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
            <param-value>client</param-value>
        </context-param>
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
            </servlet>
        <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>/faces/*</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
         <welcome-file>
                index.jsp
            </welcome-file>
        </welcome-file-list>
    </web-app>
    faces-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- =========== FULL CONFIGURATION FILE ================================== -->
    <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
      <managed-bean>
        <description>
                    The "backing file" bean that backs up the calculator webapp
                </description>
        <managed-bean-name>CalcBean</managed-bean-name>
        <managed-bean-class>secondapp.controller.CalcBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
      <navigation-rule>
        <from-view-id>/calculator.jsp</from-view-id>
        <navigation-case>
          <from-outcome>success</from-outcome>
          <to-view-id>/results.jsp</to-view-id>
        </navigation-case>
      </navigation-rule>
    </faces-config>
    secondapp.controller.CalcBean.java
    package secondapp.controller;
    import secondapp.model.Calculator;
    * @author Jonathan
    public class CalcBean {
        private int firstNumber;
        private int secondNumber;
        private int result;
        private Calculator calculator;
        /** Creates a new instance of CalcBean */
        public CalcBean() {
            setFirstNumber(0);
            setSecondNumber(0);
            result = 0;
            setCalculator(new Calculator());
        public String add(int a, int b) {
            result = calculator.add(a,b);
            return "success";
        public String multiply(int a, int b) {
            result = calculator.multiply(a,b);
            return "success";
        // <editor-fold desc=" Accessors/Mutators ">
        public int getFirstNumber() {
            return firstNumber;
        public void setFirstNumber(int firstNumber) {
            this.firstNumber = firstNumber;
        public int getSecondNumber() {
            return secondNumber;
        public void setSecondNumber(int secondNumber) {
            this.secondNumber = secondNumber;
        public int getResult() {
            return result;
        public void setCalculator(Calculator calculator) {
            this.calculator = calculator;
        // </editor-fold>
    secondapp.model.Calculator
    package secondapp.model;
    * @author Jonathan
    public class Calculator {
        /** Creates a new instance of Calculator */
        public Calculator() {
        public int add(int a, int b) {
            return a+b;
        public int multiply(int a, int b) {
            return a*b;
    calculator.jsp
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <html>
        <head><title>Calculator Test</title></head>
        <body bgcolor="white">
            <h2>My Calculator</h2>
            <f:view>
                <h:form id="calcForm">
                    <h:panelGrid columns="3">
                        <h:outputLabel value="First Number" for="firstNumber" />
                        <h:inputText id="firstNumber" value="#{CalcBean.firstNumber}" required="true" />
                        <h:message for="firstNumber" />
                        <h:outputLabel value="Second Number" for="secondNumber" />
                        <h:inputText id="secondNumber" value="#{CalcBean.secondNumber}" required="true" />
                        <h:message for="secondNumber" />
                    </h:panelGrid>
                    <h:panelGroup>
                        <h:commandButton id="submitAdd" action="#{CalcBean.add}" value="Add" />
                        <h:commandButton id="submitMultiply" action="#{CalcBean.multiply}" value="Multiply" />
                    </h:panelGroup>
                </h:form>
            </f:view>
        </body>
    </html>

    In the future, please add some line breaks so I don't have to scroll horizontally to read your post.
    The problem is that the CalcBean.add/.multiply method is requiring two parameters. This method should be parameter-less. When talking about action methods, they should return String and not take any parameters.
    So, remove the parameters. You collect a firstNumber and a secondNumber from the user. These are the numbers you want to add (or multiply). Use those values (instead of the parameters) to calculate the result.
    The code changes aren't too complicated. I'd write them out for you, but you seem interested in learning (which is great by the way!). Let me know if you need more help on this.
    CowKing
    ps - I see more problems with the code, and I haven't given you all the answers. I know, I'm mean. You'll learn better if you try to fix things on your own first. I've just given you enough info to overcome the immediate issue. =)

  • Abstract classes question

    Hi everybody,
    I have a base class called BookObject that is abstract; it has a constructor and accessors/mutators for its data members, then some abstract methods. The classes that extend it can have, as a data structure, either a list or a map, depending on what's needed. I'd like to, based on the data structure, be able to inherit certain abstract methods, but not others -- that is, the map abstract methods I wrote for when the data structure is a map, or the list methods for when the data structure is a list. If I inherit everything, it results in multiple methods with empty bodies that I don't need. Does anyone know if there is such a thing as inheriting only specified abstract methods, based on a criterion in the class? If anyone could give me any information on this, I'd appreciate it.
    Thanks,
    Jezzica85

    jezzica85 wrote:
    No, BookObject is just sort of a general wrapper class. It has subclasses like BookCharacter, BookSetting, and BookAction, for different parts of the book.Regardless, "BookObject" doesn't really tell you anything, except that it has something to do with books, and the name "Book" would tell you just as much.
    I get the impression that you might be making a single hierarchy where you don't really need it. You don't have to make every class in your project extend a particular single class in your project.
    Having subclasses called BookCharacter, BookSetting, and BookAction, doesn't necessarily make BookObject a wrapper class. What you said is a non sequiter. What exactly does BookObject wrap?
    Also I'd argue that if everything here is about books or a book, then having the word "Book" in every name doesn't help you either. Instead, having a package called "book" might be more useful, with the class names being more specific.
    From the names you've chosen, I'm going to guess that a more reasonable design and naming might have an interface called Analysis, with implementing classes named, say, BookAnalysis, CharacterAnalysis, SettingAnalysis, and ActionAnalysis. BookAnalysis would contain collections of the other analyses, and the word "Book" in the title would suggest that it's an analysis of the whole book, as opposed to elements of the book, and in fact would be one of the few objects with "Book" in its name. It wouldn't be a superclass of the other Analysis implementations -- there's no need for that.

  • Java inheritance

    Hi Guys,
    I just wanted to get your opinion on the following issue. In our
    hypothetical scenario, we would have:
    class A {
    int id;
    class B extends A {
    String name;
    Only class B is supposed to be persistent, so there would be a single JDO
    metadata file that would have 2 fields: id and name.
    Right now, it looks like when Kodo is trying to match field (from JDO
    metadata) against attributes in Java class, it does not take into
    consideration Java inheritance and as a result it complains about missing
    attribute id.
    I figure that Kodo may be parsing the java source code instead of using
    Java reflection to get the attributes.
    Any thought? I mean, we can obvuiously work around it, it is just
    something that came up recently and I wanted to see what you think about
    it.
    Thank you,
    Petr

    BTW, the reason is the enhancer can't access and wrap A's id field
    accesses...
    for example, one might have toString () { return "ID:" + id;} but since
    A has not been enhanced as PersistenceCapable, the app can access id in
    a variety of invalid states. Nor will Kodo have access to the proper
    field accessors/mutators/wrappers (esp. if id were declared private).
    Also, Kodo does -no- source examination for non-IDE based usage, either
    at enhancement time or at runtime. (the JBuilder and SunONE integration
    components use the respective IDE's code parsers to assist in metadata
    generation for uncompiled classes).
    Steve Kim wrote:
    JDO can only provide persistence for fields defined at the highest
    persistence-capable class.
    To bypass this problem a simpler solution would be:
    abstract class A {
    public abstract int getId ();
    public abstract void setId (int id);
    class B extends A
    int id;
    String name;
    // getters and setters
    And futher, if one needs concrete As (though usually that doesn't make
    sense), one can provide implementation of the abstract methods and
    override them with B's methods. Note that methods in A which access id,
    should use the accessor methods and not directly manipulate id.
    Petr wrote:
    Hi Guys,
    I just wanted to get your opinion on the following issue. In our
    hypothetical scenario, we would have:
    class A {
    int id;
    class B extends A {
    String name;
    Only class B is supposed to be persistent, so there would be a single JDO
    metadata file that would have 2 fields: id and name.
    Right now, it looks like when Kodo is trying to match field (from JDO
    metadata) against attributes in Java class, it does not take into
    consideration Java inheritance and as a result it complains about missing
    attribute id.
    I figure that Kodo may be parsing the java source code instead of using
    Java reflection to get the attributes.
    Any thought? I mean, we can obvuiously work around it, it is just
    something that came up recently and I wanted to see what you think about
    it.
    Thank you,
    Petr
    Stephen Kim
    [email protected]
    SolarMetric, Inc.
    http://www.solarmetric.com

  • Serialization output for snapshots

    I have a need to take an intial snaphost of an object as it is being created by a factory and then later take another snapshot to determine of the object or referenced objects in the graph have changed. If a change has occurred, I need to update the backing object storage. If no change has been made, then nothing is updated. This is all happening within the same thread and JVM instance. Currently I am storing the initial snapshot as a byte array from the ObjectOutputStream, taking another snapshot later and using the Arrays utilities to determine equality. This appears to work with basic testing.
    Is this consistent with the semantics of Java serialization? Am I guaranteed that an unchanged object under these conditions will produce the same serialization output?
    Thanks,
    Ben

    What mechanism would you use to create a copy ?You've 2 possibilities :
    - create a new instance of the class and fill it member by member using accessors/mutators : it could be long and prone to errors;
    - make the class implementing the Cloneable interface; example :
    public class SomeClass implements Serializable, Cloneable {
        private int number;
        public SomeClass(int number) { this.number = number; }
        public int getNumber() { return number; }
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return (SomeClass) super.clone();
    public class Test {
        public static void main(String[] args) throws CloneNotSupportedException {
            SomeClass orig = new SomeClass(10);
            SomeClass copy = (SomeClass) orig.clone();
            System.out.println("ORIGINAL REFERENCE : " + orig);
            System.out.println("    COPY REFERENCE : " + copy);
            System.out.println("TEST : " + copy.getNumber());
    Ouput :
    ORIGINAL REFERENCE : SomeClass@19821f
        COPY REFERENCE : SomeClass@addbf1
    TEST : 10
    And some of them may or may not implement a good equalsUnfortunately, this is a common error that people (including myself) are doing for purpose or not. Implementing the equals method should be mandatory for Pojo's, entity beans, and so on ...

  • Keynote presentations from iPod to TV

    As Keynote can export presentations to QuickTime, I wondered what accessories are needed to use the new video-playing iPod Nano, Classic and Touch for presenting "on the road" (or at home). These iPods all connect to a standard TV using component cables or composite cables via Apple's Universal Dock. So the necessary accessories seem to be...
    Apple Universal Dock (Includes Apple Remote and Dock Adapters to fit any of the three video-playing iPods):
    http://store.apple.com/1-800-MY-APPLE/WebObjects/AppleStore?productLearnMore=MB1 25G/A
    Apple Component AV Cable (includes Apple USB Power Adapter
    to charge your iPod at home, on the road, or whenever it's not connected to a computer.):
    http://store.apple.com/1-800-MY-APPLE/WebObjects/AppleStore.woa/wa/RSLID?mco=184 EAE7D&nplm=MB128LL/A
    Apple Composite AV Cable (includes Apple USB Power Adapter):
    http://store.apple.com/1-800-MY-APPLE/WebObjects/AppleStore.woa/wa/RSLID?mco=185 CC5FE&nplm=MB129LL/A
    ...and of course an iPod (except the Shuffle):
    http://www.apple.com/ipod/whichipod

    The iPod doesn't play visualizations, ***** up too much battery and processing power. Why not connect your computer to your TV?

Maybe you are looking for

  • Link to "Check to see if your plugins are up to date" is broken

    If i go to Tools > Addons and click on the "Check to see if your plugins are up to date" link, it gives me an error "Plugin Finding Service Error We've encountered an error. Please try your request again later." The link is sending me to https://www.

  • Illustrator CS 5.1 Error Any Help

    Runtime Error! Program:C:/Program Files (x86)/Adobe/AdobeIllus... this Application has requested the Runtime to terminate it in an unusual way. Please contact the appliction's support team for more information. I called Adobe and the support team doe

  • Fetching record from another program

    hi all,          is it possible to fetch a record from SAP database, using .NET program..... thanks in advance.

  • I'm getting an error code 9 when trying to restore apple tv 2 thru iTunes any suggestions?

    I'm getting an error code 9 when trying to restore apple tv 2 thru iTunes any suggestions?  the error comes up when itunes tries to verify the update.  I hook the apple tv back to tv and says I need to connect to itunes.  the original problem was the

  • Firefox 5.0 is slow to load Facebook???

    I hate to say it, but it seems that Firefox 5.0 takes a looooong time to load Facebook on the first open. Once it does load, Facebook moves quickly. But, close Firefox, reopen it, and reload Facebook, it's slow again. Any idea as to why? I just check