Collecting in seperate classes

I have a class that sets up one appointment called Appointment, and this needs to pass each Appointment to another class called AppointmentDiary, which stores the appointments in an ArrayList.
My question is how do I make a collection of Appointments in a different class AppointmentDiary, my code is below:
import java.util.*;
class Person {
protected String email_id;
protected String firstName;
protected String surname;
public Person() {
Person p=new Person();
public Person(String email_id, String firstName, String surname) {
this.email_id=email_id;
this.firstName=firstName;
this.surname=surname;
public String getName() {
return firstName + " " + surname;
class Manager extends Person {
private int room;
public Manager(String email_id, String firstName, String surname, int room) {
super(email_id, firstName, surname);
this.room=room;
public String getName() {
return super.getName();
public int getRoom()
return room;
class Employee extends Person {
public Student(String email_id, String firstName, String surname) {
super(email_id, firstName, surname);
public String getName() {
return super.getName();
class Appointment{
private int slot;
private String purpose;
Employee e=new Employee("js","John", "Smith");
Manager m=new Manager("jb","Jane", "Bennet", 21);
public Appointment(int slot, String purpose) {
this.slot=slot;
this.purpose=purpose;
public String getStudent() {
return s.getName();
public String getAppointment()
return s.getName() + " Has a meeting with " + l.getName() + " at " + slot + " Purpose: " + purpose + " in room " + l.getRoom();
class AppointmentDiary {
private Appointment collection;
class TestAppointment {
public static void main(String[] args) {
Appointment a=new Appointment(12, "Meeting");
System.out.println(a.getAppointment());
Thanks

import java.util.Vector;
Vector appointmentList = new Vector();
appointmentList.addElement(appointment);
//then to get them out
for(int i =0; i <appointmentList.size();i++){ //it may be length()
Appointment whatever = (Appointment)appointmentList.elementAt(i);
System.out.println(whatever.getAppointment);

Similar Messages

  • Help actionlistener in a seperate class

    Hello,
    Thank you thus far for yout help. I'm currently having a probelm with calling action listener form a seperate class file:
    The codes are as belows:
    the main class i call my action listener assaveButton = new Button("SAVE");
         saveButton.setBounds(80,350, BUTTON_WIDTH, BUTTON_HEIGHT);
         detailPanel.add(saveButton);
         saveButton.addActionListener();
    and in the other class file in which i put it as a panel i put it as:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    public class ActionTPanel extends Panel{
    public ActionTPanel(){
    cancelButton.addActionListener (
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   RecordTFrame lala = new RecordTFrame();
                   lala.show();
         saveButton.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                             try{
                             Statement stmt = con.createStatement();
                             if(!tf1.getText().equals ("")){
                             String query =     "INSERT INTO HarvestFile (" +
                                                 "TreeID, SegmentCode, DateOfHarvest, NumberOfTrees, NumberRemaining," +
                                                      "Revenue, ForestOfficer, Comments" +
                                                      ") VALUES ('" +
                                                      tf1.getText() + "','" +
                                                      tf.getText() + "','" +
                                                      tf2.getText() + "','" +
                                                      tf3.getText() + "','" +
                                                      tf5.getText() + "','" +
                                                      tf4.getText() + "','" +
                                                      tf6.getText() + "','" +
                                                      tf7.getText() + "')";
                             System.out.print("\nSending query: " +
                                                      con.nativeSQL (query) + "\n");
                             int result = stmt.executeUpdate(query);
                                  if(result==1)
                                  System.out.print("\nInsertion successful\n");
                                  else{
                                  System.out.print("\nInsertion failed\n");
                                  tf1.setText("");
                                  tf.setText("");
                                  tf2.setText("");
                                  tf3.setText("");
                                  tf5.setText("");
                                  tf4.setText("");
                                  tf6.setText("");
                                  tf7.setText("");
                             else
                             System.out.print("\nEnter Tree ID!");
                             stmt.close();
                             catch (SQLException sqlex){
                             sqlex.printStackTrace();
                             System.out.print(sqlex.toString() );
         resetButton.addActionListener (
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   tf.setText("");      
                   tf1.setText("");
                   tf2.setText("");
              tf3.setText("");
              tf4.setText("");
              tf5.setText("");
              tf6.setText("");
              tf7.setText("");
         show();
    public static void main( String args[] )
              final HAddFrame app = new HAddFrame();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    I'm not sure how to call it inthe class
    i hope u guys can help me!
    Thanks!
    -pal-
    your help is greatly appreciated!

    hello again!
    I have another question do i have to reclare the textfields in the separate class file...
    Thanks
    pal

  • Event handlers execute code from a seperate class

    i am having difficulties linking my event handlers to another piece of code in a seperate class. basically i want my event handler to execute a code which is in another class. how do i do this?

    while adding listener to the component for which u want to handle event add listener with the name of class where u r going to write the event handling code and declare that class as implementing the type of listener and handle the event in that class by implementing the definitions for the methods in the interface

  • Programs will not compile that have seperate classes

    I am trying to compile a program which has a seperate class, but it wont compile, it cant find the other class. I am compiling in the correct order, and I have tried re-compiling programs with seperate classes that I have done before, and they now wont compile. I tried compiling my program on my friends computer and it compiled fine.
    I am using jdk5.0 update 6 on Windows XP Pro
    Any help will be much appreciated

    That still doesnt work, it comes up with an extra
    error message now:
    "error reading PhoneEntry.java; error in opening zip
    file"Zip file?
    It sounds like you have some bogus zip file in your classpath.
    Did you try the exact command I posted?
    my two classes are PhoneEntry.java and
    PhoneBook.java
    PhoneEntry needs to be compiled before PhoneBookThat doesn't matter. Javac will take care of that automatically.
    PhoneEntry compiles fine, just when it tries to find
    PhoneBook it appears it cannot find the created
    PhoneEntry.class fileAll I can guess at is that you're doing this: javac -classpath .;something.zip *.java and something.zip either doesn't exist or is corrupt.

  • Include jsp versus seperate class/bean versus taglib

    Hi friends,
    I am working on Servlet/JSP project. There are large no. of jsp pages. A common set of methods get repeated in all the jsp pages. Now my concen is to separate out the methods in a file and then use it in jsp page.
    Kindly suggest me the right path to follow, taking into consideration that we take up the optimized solution and performance-wise also feasible.
    Whether I should go for
    1. Using 'include jsp'
    2. using 'taglib'
    3. creating a seperate utility class with the required methods and 'import' it in the JSP pages.
    Kindly reply ASAP.
    Thanks in advance.
    Regards.

    I would suggest you should go for user defined tags.
    This would ensure that the business functionality is isolated from your web objects and it would be modular to maintain.
    Using simple classes will add java code to your JSP pages, which makes them less readable.
    Apart from that implicit object creation by the Servlet/JSP engine(which are instantiating and garbage collecting the taglib objects) will be more efficient.
    Hope this helps
    regards
    Ravi

  • Transfer assets collectively to new class and create new assets like ABUMN

    We need to change the account determination for a few Asset Classes that already have assets with postings.  As a result we must create new asset classes and assign a new account determination.
    Is there a program that would allow transfer assets collectively to a new asset class and create new assets automatically similar to ABUMN?  T-code ABUMN allows you to transfer multiple assets but you must create the new assets first.  ABUMN will transfer and create new asset but only does one asset at a time. 
    There are hundreds of assets with postings to be transferred from the old asset classes to the corresponding new asset classes.
    Appreciate whatever input you can provide.
    Tara

    download the asset master data(original) and create new asstes using lsmw or any third party tool also.

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • Calling a method from another class while in a seperate class

    Hello
    I am currently TRYING to proramme a simple alarm clock program, The way it has had to be set out is that there are two classes one is called ClockDisplay which is just the clock and the one i have had to create is called AlarmDisplay
    I am trying to write code so that when the String alarmdisplayString(this is located in the alarm class which i am typing this code) is the same as String displayString the system will print out something like "Beep wake up" So far i have this code but i cannot figue out what to put to reference the method from the ClockDisplay class while codingi n the AlarmDisplay class
    if(alarmdisplayString = DONT KNOW WHAT TO PUT HERE) {
    system.out.println ("DING WAKE UP");
    Any help would be great!
    Thanks

    That makes sense i have put in this code
    private void Alarmtone()
    ClockDisplay displayString = new ClockDisplay();
    if (alarmdisplayString == ClockDisplay.displayString){
    system.out.println ("DING WAKE UP");
    displayString is the method in the ClockDisplay Class
    alarmdisplayString is the method in the AlarmDisplay class
    I get the error message "non-static variable displayString cannot be referenced from a static context
    Thanks for the help so far :D

  • Using variables in 5 instances of one Class in a seperate Class

    I have 5 instances of the one Class all returning different values. These values are parameteres for a final calculation. I am using Sliders as my data validation and I want my final calculation to react to the individual sliders being moved. I need to know the name of the slider and its value or do I?
    I would like to Calculate Tractive effort in Extra Panel, I know that all this has something to do with Event Handling but what?
    Any and help vastly appreciated otherwise I am goint to eat this computer cables and all.
    By the way I Hate Computers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Code as follows:
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TractiveEffortCalculator extends JFrame
         private static final long serialVersionUID = 1L;
         public ConstructParametersPanel Instance = new ConstructParametersPanel();
         public ExtraPanel Sample = new ExtraPanel();
         public JPanel thisPanel;
         public TractiveEffortCalculator()
              thisPanel = new JPanel();
              //super ("N Generation Steam"+"           "+"Tractive Effort Calculator");
              BackGroundColour myColor = new BackGroundColour();
              //ConstructParametersPanel Instance = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(2);
              grid.setHgap(10);
              grid.setRows(1);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              thisPanel.add(Instance.ConstructParametersPanelMethod());
              thisPanel.add(Sample.ExtraPanelMethod());
              setBackground(myColor.NewBackGroundColour());
              getContentPane().add(thisPanel);
              pack();
              setVisible(true);
              setLocation(40,50);
              setSize(800,600);
              //setResizable(false);
         public static void main(final String[]args)
              final TractiveEffortCalculator app = new TractiveEffortCalculator();
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    public class ConstructParametersPanel extends JPanel
         private static final long serialVersionUID = 1L;
         private JPanel sidePanel;
         TheSliderClass Instance1 = new TheSliderClass();
         TheSliderClass Instance2 = new TheSliderClass();
         TheSliderClass Instance3 = new TheSliderClass();
         TheSliderClass Instance4 = new TheSliderClass();
         TheSliderClass Instance5 = new TheSliderClass();
         public JPanel ConstructParametersPanelMethod()
              sidePanel = new JPanel();
              BackGroundColour myColor = new BackGroundColour();
              GreenColour myColor2 = new GreenColour();
              BlackShadowColour myColor3 = new BlackShadowColour();
              sidePanel.setBorder(BorderFactory.createBevelBorder(1
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()));
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              sidePanel.setLayout(grid);
              sidePanel.setBackground(myColor.NewBackGroundColour());
              sidePanel.add(Instance1.TheSliderClassMethod("Boiler Pressure",200,320));
              sidePanel.add(Instance2.TheSliderClassMethod("Wheel Diameter",60,80));
              sidePanel.add(Instance3.TheSliderClassMethod("Stroke",10,20));
              sidePanel.add(Instance4.TheSliderClassMethod("Piston Rod",2,4));
              sidePanel.add(Instance5.TheSliderClassMethod("Tail Rod",1,3));
              return sidePanel;          
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.NumberFormatter;
    public class TheSliderClass extends JPanel implements ChangeListener
         private static final long serialVersionUID = 1L;
         //Add a formatted text field to supplement the slider.
         public JFormattedTextField textField,textField2;
         public String publicSliderName = "";
         public int fps;
         //And here's the slider.
         public JSlider sliderParameterValue;
         JPanel labelAndTextField,allTogether;
         int TractiveEffort = 0;
         public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
              JPanel allTogether = new JPanel();
              Font font = new Font("palatino linotype regular", Font.BOLD, 12);
              int initialValue = ((minimumValue+maximumValue)/2);
              int tickMarkValue = (maximumValue-minimumValue);
              publicSliderName = sliderName;
              //Create the label.
              JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
              sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
              sliderLabel.setFont(font);
              sliderLabel.setForeground(Color.BLUE);
              //Create the formatted text field and its formatter.
              java.text.NumberFormat numberFormat =
                   java.text.NumberFormat.getIntegerInstance();
              NumberFormatter formatter = new NumberFormatter(numberFormat);
              formatter.setMinimum(new Integer(minimumValue));
              formatter.setMaximum(new Integer(maximumValue));
              textField = new JFormattedTextField(formatter);
              textField.setValue(new Integer(initialValue));
              textField.setColumns(3); //get some space
              textField.setEditable(false);
              textField.setForeground(Color.red);
              textField2 = new JFormattedTextField(formatter);
              textField2.setValue(new Integer(initialValue));
              textField2.setColumns(3); //get some space
              textField2.setEditable(false);
              textField2.setForeground(Color.red);
              //Create the slider.
              sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
              minimumValue, maximumValue, initialValue);
              sliderParameterValue.addChangeListener(this);
              //Turn on labels at major tick marks.
              sliderParameterValue.setMajorTickSpacing(tickMarkValue);
              sliderParameterValue.setMinorTickSpacing(10);
              sliderParameterValue.setPaintTicks(true);
              sliderParameterValue.setPaintLabels(true);
              sliderParameterValue.setBorder(
              BorderFactory.createEmptyBorder(0,0,0,0));
                                                      sliderParameterValue.setBackground(Color.cyan);
              //Create a subpanel for the label and text field.
              JPanel labelAndTextField = new JPanel(); //use FlowLayout
              labelAndTextField.setBackground(Color.cyan);      
              labelAndTextField.add(sliderLabel);
              labelAndTextField.add(textField);
              //Put everything together.
              GridLayout gridThis = new GridLayout();
              gridThis.setColumns(1);
              gridThis.setRows(2);
              allTogether.setLayout(gridThis);
              allTogether.add(labelAndTextField);
              allTogether.add(sliderParameterValue);
              allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
                                                                                    Color.red));
              return allTogether;
         /** Listen to the slider. */
         public void stateChanged(ChangeEvent e)
              JSlider source = (JSlider)e.getSource();
              fps = (int)source.getValue();
              textField.setText(String.valueOf(fps));
              textField2.setText(String.valueOf(fps));
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    public class ExtraPanel extends JPanel
         private static final long serialVersionUID = 1L;
         public JPanel thisPanel;
         public ConstructParametersPanel aPointer;
         public JPanel ExtraPanelMethod()
              thisPanel = new JPanel();
              aPointer = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              return thisPanel;

    I don't know if anyone's going to go through all that code...but here's a hint.
    if you have 5 sliders and each one represents a separate variable you're going to use in your calculation...you will need to be able to read the change in THAT PARTICULAR slider to update that particular variable and recalculate.
    So you have a change state listener: The ChangeEvent passed to the
    public void stateChanged(ChangeEvent e) method will have a method called getSource() which you use. However, you aren't figuring out which slider it came from, you're just updating the text areas with info that comes from ANY slider.
    You can use e.getSource() to identify which slider it came from.
    Say you had the following JSlider sl1, sl2, sl3, sl4.
    And each one represents int int1, int2, int3, int4;
    what you do in your stateChanged code say
    if (e.getSource()==sl1){
    int1 = sl1.getValue();
    } else if (e.getSource()==sl2){
      int2 = sl2.getValue();
    } now you have identified which slider was activated. Hope this helps!

  • Event handling in seperate class

    hello... i have a gui w/ a series of combo boxes, text fields, etc. (call this the GUI file)
    upon pressing a button, i need to run a series of event handling that will use info from many of these components
    i would like to create a separate java file for the button event handling, but need this file to have access to many componets in the GUI file - does anyone know a nice way to do this?

    i'm not quite sure how to do that... in my GUI class,
    I construct the actuall gui within the constructor..
    then i have a simple driver that creates an instance
    of class GUI and calls the constructor... how can I
    pass a reference of the GUI to the handler in that
    scenario??it would be better if you post your code. Some people like me can't just imagine.

  • Accessing interface components from a seperate class

    Hi there,
    I've just been given a Java project to build, that involves writing an applet to allow text based communication between pairs of people. I've always thought the best way to go about it was to divide code into functional units, i.e. put the user interface code in one class and the code that responds to user interface interactions in other classes (of the same package).
    The problem is getting the other classes to access the interface components created in the interface class.
    So for brevity, here is my interface Applet class;
    package name;
    import statements here;
    public class Communicate extends Applet {
    declare all variables, strings, labels, combo boxes etc
    //Construct the applet
    public Communicate() {
    try {
    jbInit();
    } catch (Exception ex) {
    ex.printStackTrace();
    //Initialize the applet
    public void init() {
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    add components here
    //Now the problem. In the interface there are combo boxes. When the user clicks a button it constructs a jframe that asks the user for a string. The idea is that the string be added to a combobox using add item. If I leave this code in the applet class it works fine, e.g.
    public void jButton5_actionPerformed(ActionEvent actionEvent) {
    JFrame f = new JFrame();
    f.setSize(200, 200);
    f.setLocation(200, 200);
    f.setVisible(false);
    //Add those boxes to the JFrame
    JTextField titleField = new JTextField();
    String title = "Please enter the title";
    int result = JOptionPane.showOptionDialog(f,
    new Object[] { message },
    "New title", JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, null, null);
    String title = titleField.getText();
    jComboBox2.addItem(title);
    //as jComboBox2 is decalred in the applet above, it adds the string no problem.
    But what I'd like is the following, a title class on its own to make it easier to update and modify,
    e.g.
    public void jButton5_actionPerformed(ActionEvent actionEvent) {
    try {
    Title title = new Title();
    catch (Exception ex) {
    ex.printStackTrace();
    with the Title class written as such:
    package name;
    import statements;
    class Title {
    Title() {
    //Set the new title
    JFrame f = new JFrame();
    f.setSize(200, 200);
    f.setLocation(200, 200);
    f.setVisible(false);
    //Add those boxes to the JFrame
    JTextField titleField = new JTextField();
    String title = "Please enter the title";
    int result = JOptionPane.showOptionDialog(f,
    new Object[] { message },
    "New title", JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, null, null);
    String title = titleField.getText();
    *** Here is the problem: How do I reference jComboBox2 which is declared in the original applet class?
    jComboBox2.addItem(title); (this wont work!)
    public static void main(String[] args) {
    Title title = new Title();
    I'd thought perhaps I needed to create an instance of the applet and pass it to the second class to use it, so it can reference the components, but I'm not sure how to do this with an applet.
    Thanks
    Maria

    I'm not going to look at your unformatted code, but I'll give you some general hints:
    Have one set of classes being the GUI
    Have one set of classes being the data (the chat history, basically)
    Have one set of classes being the logic
    Have one interface for the logic to manipulate the data (e.g. addNewMessage(String)
    Have one interface for the GUI to get the data that's to be displayed (e.g. getLastTenMessages())
    Have one interface for the logic to notify the GUI of changed data (refresh())
    Have one interface for the GUI to notify the logic of user input (e.g. sendMessage(String))
    The logic will receive data either from the user and send it, as well as storing it in your chat log, or it will receive it from the network and add it to the data model, both times notifying the GUI of changes afterwards.

  • Two seperate class files can not resolve (pls help me) THANKS!

    When i compile UseMusic.java i get the following:
    i can't figure it out..
    Thank You for Time!
    D:\java\cENG310\Ass2>javac UseMusic.java
    UseMusic.java:29: cannot resolve symbol
    symbol  : variable middlec
    location: class UseMusic
                       mm.caldis(middlec);  // compute freqs
                                 ^
    UseMusic.java:42: cannot resolve symbol
    symbol  : variable middlec
    location: class UseMusic
             mm.setzero(middlec); // reset middlec to zero
                        ^
    UseMusic.java:56: caldis(java.lang.String[],double[],double) in Music cannot be appli
                      mm.caldis(middlec);  // compute freqs
                        ^
    UseMusic.java:81: checkvaild(java.lang.String[],java.lang.String) in Music cannot be
    a.lang.String)
                boolean cv = mm.checkvaild(strkey);
                               ^
    UseMusic.java:86: getfreq(java.lang.String[],java.lang.String) in Music cannot be app
    ang.String)
                   int index = mm.getfreq(strkey);
                                 ^
    5 errors
    *  Filename    : UseMusic.java
    import iopack.Io;
    import java.text.DecimalFormat;
    * UseMusic this class is
    public class UseMusic {
          public static void main(String[] args) {
             Music mm = new Music();
                   DecimalFormat fmt = new DecimalFormat("0.###"); // round output to 3 decimals places
             boolean newmidc = false;
             boolean notelookup = false;  
             System.out.println("\n\tMusical Scales");
             System.out.println("\t---------------");     // display the title and instructions
             System.out.println("\n\tDefault note values are:");  
                 mm.caldis(middlec);  // compute freqs
             System.out.println("\n\t************************");
             System.out.println("\t* Notes  *  Frequency  *");
             System.out.println("\t************************"); 
             // print old results
             for (int i = 0; i < mm.noteName.length; i ++) {
                        // display values onto screen
                System.out.println("\t* " + mm.noteName[i] + "\n");
                System.out.println("      " + mm.noteFreq[i] + " Hz *\n");     
             mm.setzero(middlec); // reset middlec to zero
             // prompt user for value of midddle c
             while (!newmidc) {
                   //read value new value for middle c
                   double middlec = Io.readDouble("\n\tEnter value for Middle C [Between 250 - 265] (Hz)");
                   // vaildate value for middlec
                   // vaild if valeu for middle is between 250-265
                   if ((middlec > 250) && (middlec < 265)) {
                      System.out.println("\n\tNew note values");
                      System.out.println("\n\t----------------\n");
                      mm.caldis(middlec);  // compute freqs
                      System.out.println("\n\t************************");
                      System.out.println("\t* Notes  *  Frequency  *");
                      System.out.println("\t************************"); 
                      // print old results
                      for (int i = 0; i < mm.noteName.length; i ++) {
                            // display values onto screen
                            System.out.println("\t* " + mm.noteName[i] + "\n");
                            System.out.println("      " + mm.noteFreq[i] + " Hz *\n");     
                      break;   // get out of while
                   else {
                         System.out.println("\nError Invaild Input!\nValue must be between 250 Hz to 265 Hz.");         
                   } //end of else
             } // end of while for newmidc
             // prompt user for note
             while (!notelookup) {
                //read value new value for
                String strkey = Io.readString("\n\tEnter note value");
                boolean cv = mm.checkvaild(strkey);
                // vaildate value for middlec
                // vaild if valeu for middle is between 250-265
                if (cv == true) {
                   int index = mm.getfreq(strkey);
                   System.out.println("\nNote " + mm.getnoteName(index) + "has frequency of" + mm.getnoteFreq(index) + " Hz");
                   break;   // get out of while
                else {
                   System.out.println("Invaild note!, please try again.");          
                } //end of else
             } //end of while    
          }// end of static main
    } // end of Class UseMusic
    *  Filename    : Music.java
    import java.*;
    public class Music
       static int MAXSIZE = 12;                  // max # of elements (13 elements)
       static double INITALMIDDLEC = 256;     // set default value of middle c to 256
       double middlec;          // user value for middlec
       String[] noteName;   // array stores name of notes
       double[] noteFreq;     // array stores freq of notes
      boolean vaildstr;     // track whether entered string is vaild
       char replay;               // user's reponse to continue prompt
       boolean uContinue;     // whether or not to continue
       int sub;                         // index of searched string
       // Default Constructor
       Music () {
          String[] noteName = {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B","C'"};
          double[] noteFreq = new double[noteName.length];
          middlec = INITALMIDDLEC; // default value of middlec to 256
              vaildstr = false;        // signify whether user entered value
          sub = 0;
       void caldis(String[] noteName, double[] noteFreq, double middlec) {
          // calculate the values based upon middlec
          double temp = 0; // dummy used to store value
          double semitone = (double)Math.pow(2,(1/12));
          temp = middlec;   //set the value of the first element to middlec   
          // fill noteFreq with values wrt middlec
          // no magic #s - noteName since noteFreq has # of elements
          for (int i = 0; i < noteName.length; i++) {
             temp = noteFreq[i-1]; // save value of previous elements 
             noteFreq[i] = temp + (temp * semitone);
          } //end of for
       double getmiddlec(double middlec) {
          return middlec;   // Returns the value of middlec
       int getfreq(String[] noteName, String strkey) {     
          for (int i = 0 ; i < noteName.length ; i++) {        
             if (strkey.compareTo(noteName) == 0) {           
    sub = i;
    return sub;
         double setzero(double middlec) {
              middlec = 0;
              return middlec;
    String getnoteName(int index) {
    return noteName[index];
    double getnoteFreq(int index) {
    return noteFreq[index];
    boolean checkvaild(String[] noteName, String strkey) {
    vaildstr = noteName.equals(strkey);
    return vaildstr;
    } //end of Class Music

    >
    What part can't you figure out? The compiler is
    telling you that it can't resolve "middlec", which it
    can't, because you apparently didn't define it
    anywhere. Actually he did define it, but he defined it after he passed it to those methods. If that's not simply an oversight on his part, I can't begin to understand what he was thinking.

  • Program Design Problem: Inner Class use verse interacting seperate classes?

    i am designing a GUI based program that needs to have 2+ windows that interact with each other. In my original design there were just two windows: the World display, and the tile choser (this is for 2D map editing). Because there were only 2, I made them both inner classes of another class. The top level class's fields were how I got the two windows to interact.
    Now I am adding more tile choser esque windows and it is getting very confusing and the amount of Fields is getting ridiculous and the whole thing isnt very OO.
    I thought about splitting up the World Display window and the Tile Choser window into two different classes and just have multiple instances of the Tile Choser class for the additional windows.
    The problem is the interaction. I could pass all of the variables that both classes require to constructers and set up lots and lots of get and set methods, but then that seems to destroy the whole idea of two classes. The whole project is getting really messy.
    Any thoughts?
    I know that was a jarbled explanation so just ask about any part that might be unclear

    Create an object that represents the state being manipulated. The model.
    Create methods to modify that data. Not getters/setters, but controllers. If it's a map, then maybe a method would be "addTown" or something. This represents the controller.
    Create methods to render the data graphically. The views.
    Pass this object to GUI widgets, or reference it from inner event handlers.

  • 2 seperate class files, need some help

    Hi,
    Um, incase you didn't notice, I'm new to java. The closest to Java that I've ever been was C#. But anyways:
    I have 2 class files. One of them is a main form, and the other one is a simple dialog form. Is there a way that I can make the main form show the dialog form say, by clicking a button? I know how to create a button and do something when the button is clicked, I just don't know how to make one form show another one without having the code for both forms in one file. By the way, I'm making it in Swing if that makes a difference. Also, code examples would help, thanks.

    Hi,
    Um, incase you didn't notice, I'm new to java.The way about every second posts starts in here. Thanks for pointing it out, I wouldn't have guessed. :p
    The
    closest to Java that I've ever been was C#. But
    anyways:
    I have 2 class files. One of them is a main form, and
    the other one is a simple dialog form.
    Is there a way
    that I can make the main form show the dialog form
    say, by clicking a button?Yes, of course.
    I know how to create a
    button and do something when the button is clicked, I
    just don't know how to make one form show another one
    without having the code for both forms in one file.Uhm. Just something similar to
    MyDialog d = new myDialog(theFrameToBeModalTo);
    d.show();?
    What does it have to do with files? Java doesn't care about files.
    By the way, I'm making it in Swing if that makes a
    difference. Also, code examples would help, thanks.All code examples you need are here:
    http://java.sun.com/docs/books/tutorial/

  • Static class garbage collection

    Can garbage collector can garbage collect static classes ?.
    My doubt is that when you access a static class , that class is loaded through its class loader ( when first time that class is referenced ).
    So when did the garbage collector collects this static class ( assume that static class no longer referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a particular class ( Assume that i m implementing a singleton for my java runtime)
    thanks and regards
    Renjith.

    Can garbage collector can garbage collect static classes ?. Static classes are nothing special in terms of class loading - they are only different in visibility for linking.
    Perhaps you mean static members of classes?
    My doubt is that when you access a static class ,
    that class is loaded through its class loader ( when
    first time that class is referenced ). Classes are always loaded through classloaders. Objects of those classes are allocated from the heap, and the object instances refer to the class object.
    Objects (either instances, or classes themselves) are garbage collected when they are no longer live (i.e. no live object refers to them). (This is a somewhat recursive definition, and sometimes, you can have cyclic dependencies that make garbage collection tricky, but the GC, while it has to be conservative for correctness, usually gets it right).
    So for a static member to be garbage-collected, the class has to be garbage-collected first. The class cannot be GC'ed until all references to it go away (this includes all dynamically allocated objects of that type, and the class loader that loaded that class).
    And yes, class loaders can go away, but only if they are created by your program. The system class loader (which is the default classloader you get if you don't create any class loaders of your own) never goes away, so any class loaded from CLASSPATH will never be unloaded.
    (As an example, servlet containers - e.g. Tomcat, Weblogic, etc.) allocate one or more classloaders for each webapp. When the webapp is un-deployed, the classloaders are "orphaned", and they, and any classes loaded by them (from the WEB-INF/lib and WEB-INF/classes directories) are unloaded and garbage-collected. (After all the dynamic objects of those classes are GC'ed, of course).
    >
    So when did the garbage collector collects this
    static class ( assume that static class no longer
    referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a
    particular class ( Assume that i m implementing a
    singleton for my java runtime)
    thanks and regards
    Renjith.

Maybe you are looking for

  • Creating a new user (not database) in an E Business Suite application

    Hi My company has an old test application that we cant get into at the minute as we dont have any credentials to do so. Does anyone know how to create a new user? also does anyone know how to change the password of an existing user? Thanks in advance

  • Adding photo titles in web gallery iPhoto 8

    When I publish photos to the web gallery in iPhoto 8 I have "show photo titles" checked in the options yet the titles never appear in the published album. What am I doing wrong?

  • Using "share" function to Email photos in 11

    When using the "share" function to EMAIL phtos, they seem to go but do NOT show up in my SENT folder on my email. Does proof the email and photos being sent show up anywhere else?

  • Cost center validation while creating PO

    Hi, How can we put a cost center validation in PO. we are experiencing issues with PO's created for a different company code at the time of posting invoices. how can we put a check while creating a PO to validate the cost center. Can we put a check o

  • Mail 3.5 doesn't expunge on an IMAP

    Running 10.5.6. Mail v3.5. Spamcop is my IMAP server. I have the IMAP settings in Mail set to leave deleted messages on server and also to move deleted messages to the Trash. I have selected the appropriate IMAP mailbox for Trash. When I delete an em