Help with constructor

Hello, Im trying for hours and Im having trouble understanding why my code is not working. I added a private instance variable called birthDate that uses a class called Date(3 private int var. for day, month, year). I adjusted the constructor to have 3 more integer arguments to add in the Date. I would like to return the birth month of a person when i run it. This is what I have...any help is very much appreciated.
public abstract class Employee {
   private String firstName;
   private String lastName;
   private String socialSecurityNumber;
   private Date birthDate;     //private instance variable birthDate(class Date)
   // constructor
   public Employee( String first, String last, String ssn, int bMonth, int bDay, int bYear)
      firstName = first;
      lastName = last;
      socialSecurityNumber = ssn;
          birthDate.day = bDay;
       birthDate.month = bMonth;
       birthDate.year = bYear;
// public method getBirthMonth() - return the birth month of person.
   public int getBirthMonth()
     return bMonth;
   }As well, i would like to add a method that will check the persons month against the calender month and return either 0 or 100 to get a bonus.
This is what i tried but not sure if it is correct...
// method to calculate bonus
     public double bonus(int month)
          Calendar now = Calendar.getInstance();               // declare local system date
          int thisMonth = now.get(Calendar.MONTH);          // get this month, 0 for January
          System.out.print("This month is: " + thisMonth);      // print this month
          g.drawString("This month is: " + thisMonth, 25, 25); // print this month as used in applets
          if ( thisMonth == month)    // validate the month
          {  return 100;  }
          else { return 0; }
     }Can anyone help me solve this...Thank you and have a good day. :)

this is my date class:
public class Date {
   private int month;  // 1-12
   private int day;    // 1-31 based on month
   private int year;   // any year
   // constructor: call checkMonth to confirm proper value for month;
   // call checkDay to confirm proper value for day
   public Date( int theMonth, int theDay, int theYear )
      month = checkMonth( theMonth ); // validate month
      year = theYear;                 // could validate year
      day = checkDay( theDay );       // validate day
      System.out.println( "Date object constructor for date " +
         toDateString() );
   } // end Date constructor
   // utility method to confirm proper month value
   private int checkMonth( int testMonth )
      if ( testMonth > 0 && testMonth <= 12 )  // validate month
         return testMonth;
      else { // month is invalid
         System.out.println( "Invalid month (" + testMonth +
            ") set to 1." );
         return 1;  // maintain object in consistent state
   } // end method checkMonth
   // utility method to confirm proper day value based on month and year
   private int checkDay( int testDay )
      int daysPerMonth[] =
         { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
      // check if day in range for month
      if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
         return testDay;
      // check for leap year
      if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
           ( year % 4 == 0 && year % 100 != 0 ) ) )
         return testDay;
      System.out.println( "Invalid day (" + testDay + ") set to 1." );
      return 1;  // maintain object in consistent state
   } // end method checkDay
   // return a String of the form month/day/year
   public String toDateString()
      return month + "/" + day + "/" + year;
} // end class Date

Similar Messages

  • Help with constructors, accessors and mutators

    Hi all...
    Can anyone give me a code for the following problem with the use of constructors, accessors and mutators ?
    Programme is :
    Create a class called Stock that has the following attributes:
    STKID : integer
    DESC : STRING
    COSTPRICE : float
    SALEPRICE : float
    QTY : integer
    Create constructors, accessors and mutators for the above class.
    Create an array of object that can store up to 100 of the above objects.
    Implement the following functionalities:
    Add new Stock Record
    Search Stock Record
    Delete Stock Record
    Update Stock Record
    Its quite urgent, since I got to submit this for my interview tomorrow. So if anyone knows the code please do reply. Thanks in advance.
    Thanks and Regards,
    Jayanth.

    @jayanth: Ignore these guys - they're just sour and don't understand the value of helping each other out. Besides, I'm bored, and this was an easy write-up. I can send the code to your email ([email protected]) if you'd like. Just let me know.

  • Need help with constructors

    Here is my InventoryMain.java, Inventory.java, and Maker.java.
    I am having trouble with my constructors in Maker.java. Here is the line (this line is at the bottom of my Maker.java)
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
                   Double.parseDouble(txtfield1[6].getText()));here is my error when compiling:
    symbol : constructor Maker(java.lang.String,java.lang.String,double,int,java.lang.String,int,double)
    location: class inventorymain.Maker
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
    1 error
    BUILD FAILED (total time: 0 seconds)
    I have tried all kinds of different orders trying to match my constructors for Inventory(). Nothing seems to work. Can anyone help????
    InventoryMain.java
    package inventorymain;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import javax.swing.JFrame;
    public class InventoryMain
        // main method begins execution of java application
        public static void main(String[] args)
            //variables
            double restockFee = 0.05;
            //create array for products in inventory
            //enter elements into array
            Maker p = new Maker( 5186521, "pens", 1.59, 346, "Bic", restockFee);
            Maker q = new Maker( 9486452, "pencils", .59, 487,"Mead", restockFee);
            Maker r = new Maker( 6317953, "markers", 1.29, 168,"Sharpie", restockFee);
            Maker s = new Maker( 5152094, "paperclips", 1.19, 136,"Dennison", restockFee);
            Maker t = new Maker( 4896175, "glue", .79, 72,"Elmer's", restockFee);
            Maker u = new Maker( 5493756, "tape", .49, 127,"3m", restockFee);
            Maker v = new Maker( 6537947, "paper", 1.79, 203,"Mead", restockFee);
            Maker w = new Maker( 7958618, "staples", 1.19, 164,"Pentech", restockFee);
            Maker x = new Maker( 5679139, "folders", .49, 238,"Mead", restockFee);
            Maker y = new Maker( 7689110, "rulers", .17, 123,"Stanley", restockFee);       
            p.ShowInventory();
         p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         p.setVisible(true);
         p.setSize(520, 490);
          }//end main
    }//end class Inventory____________________________
    Inventory.java
    package inventorymain; //file assigned to inventorymain package
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    public class Inventory extends JFrame
            // set variables
            private Container cp = getContentPane();
            private static int itemNum[] = new int[100];
            private static String name[] = new String[100];
            private static int units[] = new int[100];
            private static double price[] = new double[100];      
            private static int i = 0;
            public Inventory()
                setLayout(new FlowLayout());
            public Inventory(int _itemNum, String _name, double _price, int _units)//varibles for constructor
                itemNum[i] = _itemNum;//variable initialized
                name[i] = _name;//variable initialized
                units[i] = _units;//variable initialized
                price[i] = _price;//variable initialized
                i = i + 1;
            // All setters and getters
            public static int getItemNum(int k)
                return itemNum[k];
            public static String getItemName(int k)
                return name[k];
            public static int getItemUnits(int k)
                return units[k]; 
            public static double getItemPrice(int k)
                return price[k];
            public static void setItemNum(int k, int value)
                itemNum[k] = value;
            public static void setItemName(int k, String value)
                name[k] = value;
            public static void setItemUnits(int k, int value)
                units[k] = value;
            public static void setItemPrice(int k, double value)
                price[k] = value;
            public static void DeleteItem(int k)
                for(int j=k; j<getCount()-1; j++)
                    setItemNum(j, getItemNum(j + 1));
                    setItemName(j,getItemName(j+1));
              setItemUnits(j,getItemUnits(j+1));
              setItemPrice(j,getItemPrice(j+1));
                }//end for
                i-=1;
            }//end DeleteItem
            public static int SearchItem(String value)
                int k = -1;
                for(int j=0;j<getCount();j++)
              if(getItemName(j).equals(value))
                        k = j;
                }//end for
                return k;
         }//end SearchItem
            public  static double totalOfInventory(double p, int u)//computes value of all merchandise in inventory
                return p * u;
            }//end method totalOfInventory
            public static void swap(int j, int min)
                String tmp;
                tmp = name[j];
                name[j] = name[min];
                name[min] = tmp;
                int temp = itemNum[j];
                itemNum[j] = itemNum[min];
                itemNum[min]= temp;
                temp = units[j];
                units[j] = units[min];
                units[min] = temp;
                double temp1 = price[j];
                price[j] = price[min];
                price[min]= temp1;
            }//ends swap method
            public double showTotalOfInventory()
                double totalValue = 0;
                for (int j = 0; j < getCount(); j++)
                    totalValue = totalValue + totalOfInventory(price[j], units[j]);
                return totalValue;
            }//end showTotalOfInventory
            public static int getCount()
                return i;
    }// end class Inventory
    class Products
        public static double totalOfInventory(double p, double u, double rf)
            double tOfI = (p * u) + (p * u * rf);
            return (tOfI);
        public static double totalOfRestockFee(double p, double rf)
            double percent = 0;
            percent = (p * 5) / 100;
            return percent;       
    }//end class Products_______________________________
    Maker.java
    package inventorymain;
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    class Maker extends Inventory implements ActionListener
    {//begins Class Maker
        static String manufact[] = new String[100];
        static double restockingFee[] = new double[100];
        static int i;
        static double TotalVal;
        static int navItem;
        static Boolean isRecordLoadedFromFile = false;
        private Container cp = getContentPane();
        GridBagConstraints c;
        GridBagConstraints cconstraint;
        Border titledborder;
        JPanel pan;
        String labels[] = {"Product Name:", "Manufacturer:", "Product ID Number:", "Units in Stock:", 
                           "Price Per Unit:                                                      $",
                           "Restocking Fee:                                                   $",
                           "Value of Product in Stock:                                $",
                           "Value of All Merchandise Plus Restocking: $"};
        int len1 = labels.length;
        JLabel lbl[] = new JLabel[len1];
        JTextField txtfield1[] = new JTextField[len1];
        String blabels[] = {"First", "Previous", "Next", "Last"};
        int blen = blabels.length;
        JButton navigate[] = new JButton[blen];
        String cmdlabels[] ={"Load File", "Add", "Modify", "Delete", "Search", "Save","Cancel" };
        int cmdlen = cmdlabels.length;
        JButton cmdbutton[] = new JButton[cmdlen];
        JLabel lblImg;
        File file;
        public String FileName;
        public Maker(int Item_Number, String Item_Name, double Item_Price, int Items_in_Stock, String manufact, double restockingFee)// Constructor for varibles
            super(Item_Number, Item_Name, Item_Price, Items_in_Stock);
            this.manufact[i] = manufact;
            this.restockingFee[i] = restockingFee;
            i = i + 1;
        public static void setManufact(int k, String value)
            manufact[k] = value;
        public static double getRestockFee(int val)
            return restockingFee[val];
        public void ShowInventory()
            setLayout(new FlowLayout());
            GridBagLayout contlayout = new GridBagLayout();//layout for container
            GridBagConstraints cconstraint = new GridBagConstraints();//constraint for container
            GridBagLayout gblayout = new GridBagLayout();//layout for panel
            GridBagConstraints gbconstraint = new GridBagConstraints();
            FileName = "C://dat//inventory.dat";
            try
                String strDirectoy = "C://dat";
                boolean success = (new File(strDirectoy)).mkdir();
                file = new File(FileName);
                success = file.createNewFile();
                //ADD SAVE CANCEL DELETE EXIT
                pan = new JPanel();
                gblayout = new GridBagLayout();
                gbconstraint = new GridBagConstraints();
                pan.setLayout(gblayout);
                gbconstraint.gridwidth = 1;
                gbconstraint.gridheight = 1;
                gbconstraint.gridy = 0;
                for (int i = 0; i < cmdlen; i++)
                    cmdbutton[i] = new JButton(cmdlabels);
              cmdbutton[i].addActionListener(this);
              gbconstraint.gridx = i;
              pan.add(cmdbutton[i], gbconstraint);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Confirmation");
    pan.setBorder(titledborder);
    //ADD PANEL TO CONTAINER
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 2;
    cp.add(pan, cconstraint);
    //ADDITION COMPLETE
    //first panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    for (int i = 0; i < 2; i++)
    for (int j = 0; j < len1; j++)
    int x = i;
    int y = j;
    if (x == 0)
    lbl[j] = new JLabel(labels[j]);
    lbl[j].setHorizontalAlignment(JLabel.LEFT);
    lbl[j].setPreferredSize(new Dimension(250, 15));
    gbconstraint.insets = new Insets(10, 0, 0, 0);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(lbl[j], gbconstraint);
    }//end if
    else
    txtfield1[j] = new JTextField(15);
    txtfield1[j].setPreferredSize(new Dimension(300, 15));
    txtfield1[j].setHorizontalAlignment(JLabel.LEFT);
    txtfield1[j].setEnabled(false);
    lbl[j].setLabelFor(txtfield1[j]);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(txtfield1[j], gbconstraint);
    }//end else
    }//end for
    }//end for
    Border titledborder = BorderFactory.createTitledBorder("Current Inventory Records");
    pan.setBorder(titledborder);
    //adds panel to container
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 0;
    cp.add(pan, cconstraint);
    //add icon to display
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 0;
    lblImg = new JLabel((new ImageIcon(getClass().getResource("logo111.jpg"))));
    lblImg.setPreferredSize(new Dimension(70, 70));
    pan.add(lblImg);
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    //ends icon insert
    //navigation panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 1;
    for (int i = 0; i < blen; i++)
    navigate[i] = new JButton(blabels[i]);
    gbconstraint.gridx = i;
    pan.add(navigate[i], gbconstraint);
    navigate[i].addActionListener(this);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Navigation Panel");
    pan.setBorder(titledborder);
    //add panel to container
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 1;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    }//end try
    catch (Exception e)
    e.printStackTrace();
    }//end catch
    }//end showInventory
    public void setContents(File aFile, String aContents)
    BufferedWriter output = null;
         try
    //use buffering
    //FileWriter always assumes default encoding is OK!
    output = new BufferedWriter(new FileWriter(aFile, true));
    output.write(aContents);
    String newLine = System.getProperty("line.separator");
    output.write(newLine);
    }//end try
    catch (Exception ex)
    ex.printStackTrace();
    }//end catch
    finally
    try
    //flush and close both "output" and its underlying FileWriter
              if (output != null) output.close();
    }//end try
    catch (java.io.IOException e)
    e.printStackTrace();
    }//end catch
    public void AddModifyInventory(String Mode)
    if (Mode.equals("Insert"))
    String Content = txtfield1[1].getText() + "\t"
    + txtfield1[2].getText() + "\t" + txtfield1[3].getText()
    + "\t" + txtfield1[4].getText();
    setContents(file, Content);
    JOptionPane.showMessageDialog(null, "Record Successfully Inserted");
    }//end if
    }//end AddModifyInventory
    public void ShowInventory(int ItemNo)
    txtfield1[0].setText(Integer.toString(ItemNo));
    txtfield1[0].setText(Inventory.getItemName(ItemNo));
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(ItemNo)));
    txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(ItemNo)));
    txtfield1[4].setText(Double.toString(Inventory.getItemPrice(ItemNo)));
    txtfield1[5].setText(String.format("%3.2f",
    Products.totalOfRestockFee(Inventory.getItemPrice(ItemNo),
    getRestockFee(ItemNo))));
    txtfield1[6].setText(String.format("%3.2f",
    Products.totalOfInventory(Inventory.getItemPrice(ItemNo),
    Inventory.getItemUnits(ItemNo), getRestockFee(ItemNo))));
    txtfield1[7].setText(String.format("%3.2f", GetTotalInvVal()));
    }//end ShowInventory(int ItemNo)
    public void EnableFields(boolean bflag)
    txtfield1[1].setEnabled(bflag);
    txtfield1[2].setEnabled(bflag);
    txtfield1[3].setEnabled(bflag);
    txtfield1[4].setEnabled(bflag);
    txtfield1[5].setEnabled(bflag);
    }//end EnableFields
    public double GetTotalInvVal()
    TotalVal = 0;
    for(int j = 0; j < Inventory.getCount(); j++)
    TotalVal += Products.totalOfInventory(Inventory.getItemPrice(j),
    Inventory.getItemUnits(j), getRestockFee(j));
    return TotalVal;
    }//end GetTotalInvVal
    public Integer GetRecordCount()
         FileReader fr;
         BufferedReader br;
         LineNumberReader lnr;
         String line;
         int lno = 0;
         try
    lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
    while ((line = lnr.readLine()) != null)
              lno = lnr.getLineNumber();
         lnr.close();
         }//end try
         catch (IOException ioErr)
    System.out.println(ioErr.toString());
    System.exit(100);
         return lno;
    public void showInventory(int itemNo)
    int i;
    FileReader fr;
    BufferedReader br;
    LineNumberReader lnr;
    StringTokenizer st;
    String line;
    int item = itemNo + 1;
    int ItemNo = 0;
    int Units = 0;
    String ItemGenre = "";
    String ItemName = "";
    String ItemRating = "";
    double UnitPrice = 0;
    double Total = 0;
    Integer rFee = 0;
    int lno;
    try
              lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
              while ((line = lnr.readLine()) != null)
    lno = lnr.getLineNumber();
    String s1[];
    if (item == lno)
                   s1 = new String[lno];
                   s1[0] = line;
                   st = new StringTokenizer(s1[0]);
                   //ItemNo = lno;
                   ItemGenre = st.nextToken();                         
                   ItemNo = Integer.parseInt(st.nextToken());
                   ItemName = st.nextToken();
                   ItemRating = st.nextToken();
                   Units = Integer.parseInt(st.nextToken());
                   UnitPrice = Double.parseDouble(st.nextToken());
                   //rFee = Integer.parseInt(st.nextToken());
    }//end if
    s1 = new String[lno];
    s1[0] = line;
    st = new StringTokenizer(s1[0]);
    st.nextToken();
    st.nextToken();
    st.nextToken();
    st.nextToken();
    Integer units = Integer.parseInt(st.nextToken());
    Double price = Double.parseDouble(st.nextToken());
    Total += Products.totalOfInventory(price, units, 0.05);
    }//end while
    lnr.close();
    }//end try
    catch (IOException ioErr)
              System.out.println(ioErr.toString());
              System.exit(100);
    }//end catch
    txtfield1[0].setText(Integer.toString(itemNo));
    txtfield1[0].setText(ItemName);
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(ItemNo));
    txtfield1[3].setText(Integer.toString(Units));
    txtfield1[4].setText(Double.toString(UnitPrice));
    txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(UnitPrice, 0.05)));
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(UnitPrice, Units, 0.05)));
    txtfield1[7].setText(String.format("%3.2f", Total));          
         }//end showInventory
    public void actionPerformed(ActionEvent e)//button actions
    String btnClicked = ((JButton)e.getSource()).getText();
    if(btnClicked.equals("First"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              navItem = 0;
              showInventory(navItem);
    }//end if
    else
              navItem = 0;
              ShowInventory(navItem);
    }//end else
         }//end if
         if (btnClicked.equals("Next"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              if (navItem == GetRecordCount() - 1)
    navItem = 0;
              }//end if
    else
    navItem += 1;
              }//end else
              if ((GetRecordCount() - 1) >= navItem)
    showInventory(navItem);
    else
    showInventory(GetRecordCount() - 1);
    }//end if
    else
    if (navItem == getCount() - 1)
    navItem = 0;
    }//end if
    else
    navItem += 1;
    }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Previous"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    if (navItem == 0)
    navItem = GetRecordCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    showInventory(navItem);
    }//end if
    else
              if (navItem == 0)
    navItem = getCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Last"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    navItem = GetRecordCount() - 1;
              showInventory(navItem);
    }//end if
    else
              navItem = getCount() - 1;
              ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Save"))
    AddModifyInventory("Insert");
         }//end if
    if (btnClicked.equals("Load File"))
    isRecordLoadedFromFile = true;
    if (GetRecordCount() == 0)
              JOptionPane.showMessageDialog(null, "No Records Found in the File");                    
    }//end if
    else
              showInventory(0);
    }//end else
    if (btnClicked.equals("Cancel"))
              EnableFields(false);
              cmdbutton[4].setText("Search");
              cmdbutton[2].setText("Modify");
              cmdbutton[1].setText("Add");
    if(isRecordLoadedFromFile)
    showInventory(navItem);
              else
    ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Delete"))
              Inventory.DeleteItem(Integer.parseInt(txtfield1[0].getText()));
              navItem = getCount() -1;
              JOptionPane.showMessageDialog(null, "Record Successfully deleted");
              ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Search"))
              cmdbutton[4].setText("GO!");
              txtfield1[3].setEnabled(true);     
    }//end if
    if(btnClicked.equals("GO!"))
              boolean valid = true;
    if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
    if(valid)
    int k = Inventory.SearchItem(txtfield1[3].getText().trim());
    if(k>=0)
                   txtfield1[0].setText(Integer.toString(k));
                   txtfield1[0].setText(Inventory.getItemName(k));
    txtfield1[1].setText(manufact[k]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(k)));
                   txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(k)));
                   txtfield1[4].setText(Double.toString(Inventory.getItemPrice(k)));
                   txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(k), getRestockFee(k))));
                   txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(k ), Inventory.getItemUnits(k), getRestockFee(k))));
                   txtfield1[7].setText(String.format("%3.2f",GetTotalInvVal()));
                   EnableFields(false);
                   cmdbutton[4].setText("Search");                              
    }//end if
    else
    JOptionPane.showMessageDialog(null, "No Matches found");     
    cmdbutton[4].setText("Search");     
    EnableFields(false);
    }//end else
              }//end if               
    }//end if
    if(btnClicked.equals("Modify"))
              EnableFields(true);                         
              cmdbutton[2].setText("Click to Modify!");
    }//end if
    if(btnClicked.equals("Click to Modify!"))
              Boolean valid = true;
    if (txtfield1[1].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Genre Required");
    valid = false;
              }//end if
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
              catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (Only Numbers allowed)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              if (txtfield1[4].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Rating Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[5].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (Only Numbers allowed)");
    txtfield1[4].setText("");
    valid = false;
              }//end catch
    try
    Double.parseDouble(txtfield1[6].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Price (Only Numbers allowed)");
    txtfield1[5].setText("");
    valid = false;
              }//end catch
              if (valid)
    //setItemNum,setItemName,setItemUnits,setItemPrice
    Inventory.setItemNum(navItem,Integer.parseInt(txtfield1[1].getText()));
    Inventory.setItemName(navItem,txtfield1[2].getText());
    Inventory.setItemUnits(navItem,Integer.parseInt(txtfield1[4].getText()));
    Inventory.setItemPrice(navItem,Double.parseDouble(txtfield1[5].getText()));     
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(navItem), getRestockFee(navItem))));
    txtfield1[7].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(navItem ), Inventory.getItemUnits(navItem), getRestockFee(navItem))));
    txtfield1[8].setText(String.format("%3.2f",GetTotalInvVal()));
    EnableFields(false);
    cmdbutton[2].setText("Modify");
              }//end if
    }//end if
    if (btnClicked.equals("Add"))
              EnableFields(true);
              txtfield1[0].setText(Integer.toString(getCount()));
              txtfield1[1].setText("");
              txtfield1[2].setText("");          
              txtfield1[3].setText("0");
              txtfield1[4].setText("0.00");
              cmdbutton[1].setText("Click to Add!");
    }//end if
    if (btnClicked.equals("Click to Add!"))
    Boolean valid = true;
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (use numbers only)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[0].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[3].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (use numbers only)");
    txtfield1[3].setText("");
    valid = false;
              }//end catch
    try

    You do not need to post that massive amount of code to ask about a compile-time error.
    I (and many others here) won't even consider looking at it. Create a small example that demonstrates what you're having trouble with.

  • Help with constructors using inheritance

    hi,
    i am having trouble with contructors in inheritance.
    i have a class Seahorse extends Move extends Animal
    in animal class , i have this constructor .
    public class Animal() {
    public Animal (char print, int maxage, int speed) {
    this.print = print;
    this.maxage = maxage;
    this.speed = speed;
    public class Move extends Animal {
    public Move(char print, int maxage, int speed)
    super(print, maxage, speed); //do i even need this here? if i dont i
    //get an error in Seahorse class saying super() not found
    public class Seahorse extends Move {
    public Seahorse(char print, int maxage, int speed)
    super('H',10,0);
    please help

    It's not a problem, it's how Java works. First, if you do not create a constructor in your code, the compiler will generate a default constructor that does not take any arguments. If you do create one or more constructors, the only way to construct an object instance of the class is to use one of the constructors.
    Second, when you extend a class, your are saying the subclass "is a" implementation of the super class. In your case, you are saying Move is an Animal, and Seahorse is a Move (and an Animal as well). This does not seem like a good logical design, but that's a different problem.
    Since you specified that an Animal can only be constructed by passing a char, int, and int, that means that a Move can only be constructed by calling the super class constructor and passing a char, int, and int. Since Move can only be constructed using a char, int and int, Seahorse can only be constructed by calling super(char, int, int);.
    It is possible for a subclass to have a constructor that does not take the same parameters as the super class, but the subclass must call the super class constructor with the correct arguments. For example, you could have.
    public Seahorse() {
       super('S',2,5);
    }The other problem is, Move does not sound like a class. It sounds like a method. Perhaps you might have MobileAnimal, but that would only make sense if there was a corresponding StationaryAnimal. Your classes should model your problem. It's hard to image a problem in which a Seahorse is a Move, and a Move is an Animal. It makes more sense for Animals to be able to move(), which allows a Seahorse to move differently compared to an Octopus.

  • Help with Constructors

    I know I'm missing something but I can't find it. I keep getting an error in the main method that is can't find the variables. I've been beating on this for two days with no luck. can anyone help?
    * @(#)Employee2.java
    * Employee2 application
    * @author
    * @version 1.00 2009/7/17
    import java.*;
    public class Employee2 {
        static String title = "Spanish Inquisitor, 3rd level";
        private String      name;
        private int      ID_num;
        private int          salary;
        private int      age;
             Employee2 (String nm, int ID, int sl, int ag){
             name      = nm;
             ID_num      = ID;
             salary      = sl;
             age      = ag;}
          int getFedTax (){
          int FedTax = (salary-800)*17/100;
          return FedTax;}
    int getSsTax(int rate){//Amount of SS tax paid
          int SsTax = salary*rate/100;
          return SsTax;}
    int getHealthFee(int rate){//health insurnce paid
          int HealthFee = salary*rate/100;
          return HealthFee;}
    int getInsurance()     {//life insurance paid depends on age
         if (age<40)     {
               return salary*3/100;
         else     {     
              if (age>=40 && age<50)     {
                    return salary*4/100;
              else     {     
                   if (age>=50 && age<60)     {
                         return salary*5/100;
                   else      {
                         return salary*6/100;
         //double getNetPay(){//Pay after taxes and fees
              //return salary-getFedTax-getSsTax-getHelthFee-Employee.getInsurance;}
    class employees {
         public static void main(String[] args) {
              Employee2 Smith = new Employee2("Filipe Smith", 121, 55000, 35);//Hello Mr. Smith
              Employee2 Chenlo = new Employee2("Sven Chenlo", 212, 90000, 56);//Hello Mr. Chenlo
         //printing requested data
         System.out.print ("Name  ");System.out.println (Smith.nm);
         System.out.print ("ID Number  ");System.out.println (Smith.ID);
         System.out.print ("Salary  ");System.out.println (Smith.sl);
         System.out.print ("Age  ");System.out.println (Smith.ag);
         System.out.print ("Job Title  ");System.out.println (Smith.title);
         System.out.print ("Federal Tax With held  ");System.out.println (Smith.getFedTax());          
         System.out.print ("Social Security With held  ");System.out.println (Smith.getSsTax(3));
         System.out.print ("Health insurance With held  ");System.out.println (Smith.getHealthFee(5));
         System.out.print ("Life insurance With held  ");System.out.println (Smith.getInsurance());
         //System.out.print ("Net Pay after Withholdings  ");System.out.println (Smith.getNetPay());
         System.out.println ();
         System.out.println ();
         System.out.println ();
         System.out.print ("Name  ");System.out.println (Chenlo.nm);
         System.out.print ("ID Number  ");System.out.println (Chenlo.ID);
         System.out.print ("Salary  ");System.out.println (Chenlo.sl);
         System.out.print ("Age  ");System.out.println (Chenlo.ag);
         System.out.print ("Job Title  ");System.out.println (Chenlo.title);
         System.out.print ("Federal Tax With held  ");System.out.println (Chenlo.getFedTax());          
         System.out.print ("Social Security With held  ");System.out.println (Chenlo.getSsTax(3));
         System.out.print ("Health insurance With held  ");System.out.println (Chenlo.getHealthFee(5));
         System.out.print ("Life insurance With held  ");System.out.println (Chenlo.getInsurance());
    //     System.out.print ("Net Pay after Withholdings  ");System.out.println (Chenlo.getNetPay());
    }

    Hi......
    You are doing two mistakes.
    1. In Employee2 Class all varible that you are accesing are defind as private access spcifier. so these variable would not be accessible outside of class. Make it public or default or anything but not private.
    2. You are accessing right side variable for printing content while you should access left hand side variables to access its value. For e.g name      = nm; Use Smith.name to print name. Do not use Smith.nm.
    So change variables of Employee2 class to public or default and access left side variable instead of right variable.
    check it out....!!!!!
    AJ09.

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help with making JLabel visible for a few seconds only

    Hello guys,
    I need help with making a JLabel object visible for a few seconds only and disappear when a JButton has been clicked.
    Here is piece of code where I add mouse listener to the JButton object in my case is (jrbFigure1) and
    when is called sets icon and text to the JLabel jlbl object:
    jrbFigure1.addMouseListener(new MouseAdapter() {
    jrbFigure1.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    jlbl.setIcon(cross);
    jlbl.setText(wrong);
    This piece of code is in a switch statement, the statement is in a method.
    The JLabel jlbl object is added in a panel in the constructor of the class.
    I really hope someone could help me on this issue.
    I would like to thank you in advance for any help or advice given.

    Bobson wrote:
    Sorry for posting my issue twice, I thought, I posted it in a wrong forum:)It's OK. We'll ask the mods to delete the other thread.
    I want the label to appear for X seconds when then button is pressed and disappear after that.Then a Swing Timer is what you want to use.
    I need to do this in a number of cases from a switch statement because I several buttons.Better to have several ActionListeners, one for each button or each type of button, rather than one ActionListener with a large switch statement, a so-called switch-board listener. They're messy to debug and upgrade.
    I tried to use Swing Timer, but I cannot set it properly.Go through the Sun Swing tutorial on Swing Timers. It's all outlined for you there: [http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]

  • Need Help With File Matching Records

    I need help with my file matching program.
    Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
    When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
    Here is my following program code:
    // Exercise 14.8: CreateTextFile.java
    // creates a text file
    import java.io.FileNotFoundException;
    import java.lang.SecurityException;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class CreateTextFile
      private Formatter output1;  // object used to output text to file
      private Formatter output2;  // object used to output text to file
      // enable user to open file
      public void openTransFile()
        try
          output1 = new Formatter("trans.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          output2 = new Formatter("oldmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openOldMastFile
      // add transaction records to file
      public void addTransactionRecords()
        // object to be written to file
        TransactionRecord record1 = new TransactionRecord();
        Scanner input1 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0) and amount.","? ");
        while (input1.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record1.setAccount(input1.nextInt());    // read account number
            record1.setAmount(input1.nextDouble());  // read amount
            if (record1.getAccount() > 0)
              // write new record
              output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input1.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
            "and amount.","? ");
        } // end while
      } // end method addTransactionRecords
      // add account records to file
      public void addAccountRecords()
        // object to be written to file
        AccountRecord record2 = new AccountRecord();
        Scanner input2 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0), first name, last name and balance.","? ");
        while (input2.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record2.setAccount(input2.nextInt());    // read account number
            record2.setFirstName(input2.next());      // read first name
            record2.setLastName(input2.next());       // read last name
            record2.setBalance(input2.nextDouble());  // read balance
            if (record2.getAccount() > 0)
              // write new record
              output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
                record2.getLastName(), record2.getBalance());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input2.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0),",
            "first name, last name and balance.","? ");
        } // end while
      } // end method addAccountRecords
      // close file
      public void closeTransFile()
        if (output1 != null)
          output1.close();
      } // end method closeTransFile
      // close file
      public void closeOldMastFile()
        if (output2 != null)
          output2.close();
      } // end method closeOldMastFile
    } // end class CreateTextFile--------------------------------------------------------------------------------------------------
    // Exercise 14.8: CreateTextFileTest.java
    // Testing class CreateTextFile
    public class CreateTextFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateTextFile application = new CreateTextFile();
         application.openTransFile();
         application.addTransactionRecords();
         application.closeTransFile();
         application.openOldMastFile();
         application.addAccountRecords();
         application.closeOldMastFile();
       } // end main
    } // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.8: TransactionRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    public class TransactionRecord
      private int account;
      private double amount;
      // no-argument constructor calls other constructor with default values
      public TransactionRecord()
        this(0,0.0); // call two-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public TransactionRecord(int acct, double amt)
        setAccount(acct);
        setAmount(amt);
      } // end two-argument TransactionRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set amount
      public void setAmount(double amt)
        amount = amt;
      } // end method setAmount
      // get amount
      public double getAmount()
        return amount;
      } // end method getAmount
    } // end class TransactionRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: AccountRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    import org.egan.TransactionRecord;
    public class AccountRecord
      private int account;
      private String firstName;
      private String lastName;
      private double balance;
      // no-argument constructor calls other constructor with default values
      public AccountRecord()
        this(0,"","",0.0); // call four-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public AccountRecord(int acct, String first, String last, double bal)
        setAccount(acct);
        setFirstName(first);
        setLastName(last);
        setBalance(bal);
      } // end four-argument AccountRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set first name
      public void setFirstName(String first)
        firstName = first;
      } // end method setFirstName
      // get first name
      public String getFirstName()
        return firstName;
      } // end method getFirstName
      // set last name
      public void setLastName(String last)
        lastName = last;
      } // end method setLastName
      // get last name
      public String getLastName()
        return lastName;
      } // end method getLastName
      // set balance
      public void setBalance(double bal)
        balance = bal;
      } // end method setBalance
      // get balance
      public double getBalance()
        return balance;
      } // end method getBalance
      // combine balance and amount
      public void combine(TransactionRecord record)
        balance = (getBalance() + record.getAmount()); 
      } // end method combine
    } // end class AccountRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatch.java
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class FileMatch
      private Scanner inTransaction;
      private Scanner inOldMaster;
      private Formatter outNewMaster;
      private Formatter theLog;
      // enable user to open file
      public void openTransFile()
        try
          inTransaction = new Scanner(new File("trans.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          inOldMaster = new Scanner(new File("oldmast.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openOldMastFile
      // enable user to open file
      public void openNewMastFile()
        try
          outNewMaster = new Formatter("newmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openNewMastFile
      // enable user to open file
      public void openLogFile()
        try
          theLog = new Formatter("log.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openLogFile
      // update records
      public void updateRecords()
        TransactionRecord transaction = new TransactionRecord();
        AccountRecord account = new AccountRecord();
        try // read records from file using Scanner object
          System.out.println("Start file matching.");
          while (inTransaction.hasNext() && inOldMaster.hasNext())
            transaction.setAccount(inTransaction.nextInt());     // read account number
            transaction.setAmount(inTransaction.nextDouble());   // read amount
            account.setAccount(inOldMaster.nextInt());     // read account number
            account.setFirstName(inOldMaster.next());      // read first name 
            account.setLastName(inOldMaster.next());       // read last name
            account.setBalance(inOldMaster.nextDouble());  // read balance
            if (transaction.getAccount() == account.getAccount())
              while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
                account.combine(transaction);
                outNewMaster.format("%d %s %s %.2f\n",
                account.getAccount(), account.getFirstName(), account.getLastName(),
                account.getBalance());
                transaction.setAccount(inTransaction.nextInt());     // read account number
                transaction.setAmount(inTransaction.nextDouble());   // read amount
            else if (transaction.getAccount() != account.getAccount())
              outNewMaster.format("%d %s %s %.2f\n",
              account.getAccount(), account.getFirstName(), account.getLastName(),
              account.getBalance());         
              theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
          } // end while
          System.out.println("Finish file matching.");
        } // end try
        catch (NoSuchElementException elementException)
          System.err.println("File improperly formed.");
          inTransaction.close();
          inOldMaster.close();
          System.exit(1);
        } // end catch
        catch (IllegalStateException stateException)
          System.err.println("Error reading from file.");
          System.exit(1);
        } // end catch   
      } // end method updateRecords
      // close file and terminate application
      public void closeTransFile()
        if (inTransaction != null)
          inTransaction.close();
      } // end method closeTransFile
      // close file and terminate application
      public void closeOldMastFile()
        if (inOldMaster != null)
          inOldMaster.close();
      } // end method closeOldMastFile
      // close file
      public void closeNewMastFile()
        if (outNewMaster != null)
          outNewMaster.close();
      } // end method closeNewMastFile
      // close file
      public void closeLogFile()
        if (theLog != null)
          theLog.close();
      } // end method closeLogFile
    } // end class FileMatch-------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatchTest.java
    // Testing class FileMatch
    public class FileMatchTest
       // main method begins program execution
       public static void main( String args[] )
         FileMatch application = new FileMatch();
         application.openTransFile();
         application.openOldMastFile();
         application.openNewMastFile();
         application.openLogFile();
         application.updateRecords();
         application.closeLogFile();
         application.closeNewMastFile();
         application.closeOldMastFile();
         application.closeTransFile();
       } // end main
    } // end class FileMatchTest-------------------------------------------------------------------------------------------------
    Sample data for master file:
    Master file                         
    Account Number            Name                     Balance
    100                            Alan Jones                   348.17
    300                            Mary Smith                    27.19
    500                            Sam Sharp                   0.00
    700                            Suzy Green                   -14.22Sample data for transaction file:
    Transaction file                    Transaction
    Account Number                  Amount
    100                                         27.14
    300                                         62.11
    300                                         83.89
    400                                         100.56
    700                                         80.78
    700                                         1.53
    900                                         82.17  -------------------------------------------------------------------------------------------------
    My FileMatch class program above has bugs in it.
    The correct results for the newmast.txt:
    100  Alan  Jones  375.31
    300  Mary  Smith  173.19
    500  Sam  Sharp  0.00
    700  Suzy Green  68.09The correct results for the log.txt:
    Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
    My results for the newmast.txt:
    100 Alan Jones 375.31
    300 Mary Smith 111.08
    500 Sam Sharp 0.00
    700 Suzy Green -12.69My results for the log.txt
    Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
    I am not sure what is wrong with my code above to make my results different from the correct results.
    Much help is appreciated. Please help.

    From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
    As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
    Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
    Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do.

  • Help with GSSAPI Kerberos in tomcat JNDIRealm

    Greetings,
    I could use some help with getting tomcat 5.5.12 to use Kerberos against Microsoft Active Directory.
    I have been using Ethereal to sniff the packets going back and forth from tomcat and I verified that with a normal server.xml entry (remove the authentication attribute keyword below), it uses 'simple'
    authentication (clear text passwords).
    My original server.xml works just fine but now I'm trying to take it to next level and I found documentation (jdk-1_5_0-doc.zip\docs\guide\jndi\jndi-ldap.html)
    specifies that there are the following values:
    - EXTERNAL (RFC 2222). This mechanism obtains authentication information from an external source (such as SSL/TLS or IPsec).
    - DIGEST-MD5 (RFC 2831) is for Digest Authentication.
    - GSSAPI (RFC 2222) is for Kerberos V5 authentication.
    I wish to use GSSAPI to talk with Active Directory so I setup my server.xml with the following :
    <Realm className="org.apache.catalina.realm.JNDIRealm"
         debug="4"
         authentication="GSSAPI"
         connectionName="CN=Klotz\, Dennis,OU=myou,DC=company,DC=com"
         connectionPassword="myPassword"
         connectionURL="ldap://10.16.0.xx:389"
         alternateURL="ldap://10.16.0.xx:389"
         userBase="OU= myou,DC=company,DC=com"
         userSearch="(sAMAccountName={0})"
         userSubtree="true"
         userRoleName="memberOf"
    />And now I get a different type of error from Catalina.out:
    Oct 28, 2005 2:28:47 PM org.apache.catalina.core.StandardHost start
    INFO: XML validation disabled
    GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos Ticket)
            at
    sun.security.jgss.krb5.Krb5InitCredential.getInstance(Krb5InitCredential
    .java:133)
    .....At least the GSSAPI is being recognized! My next step was talking with IT; they suggested a c:\winnt\krb5.ini with the following contents:
    [libdefaults]
    default_realm = COMPANY.COM
    default_tgs_enctypes = des-cbc-crc
    default_tkt_enctypes = des-cbc-crc
    [realms]
    COMPANY.COM = {
    kdc = addy.mycompany.com:88
    admin_server = addy. mycompany.com:88
    kpasswd_server = addy. mycompany.com:464 default_domain = COMPANY.COM }And that I then execute:
    $ kinit DKlotz
    Password for [email protected]:mypassword New ticket is stored in cache file C:\Documents and Settings\DKlotz\krb5cc_dklotzBut as you can see from the previous tomcat error log that something is still missing. Do I need to move the cache file or do other commands so that the code within ldap.jar can use it?
    At this time tomcat never tries connecting to the LDAP server as it can't get out of the starting gate. I've got something wrong / missing from the Kerberos setup.
    Any help is greatly appreciated!!
    -Dennis Klotz

    Ok I've made progress, whether it is backwards or not, I don't know yet.
    I've added :
    -Djavax.security.auth.useSubjectCredsOnly=false
    To my Catalina options environment variable in Catalina.bat.
    Now I get the error:
    WARNING: Exception performing authentication
    java.lang.SecurityException: Unable to locate a login configuration
         at com.sun.security.auth.login.ConfigFile.<init>(ConfigFile.java:97)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
         at java.lang.Class.newInstance0(Class.java:350)
         at java.lang.Class.newInstance(Class.java:303)
         at javax.security.auth.login.Configuration$3.run(Configuration.java:216)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.login.Configuration.getConfiguration(Configuration.java:210)
         at javax.security.auth.login.LoginContext$1.run(LoginContext.java:237)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.login.LoginContext.init(LoginContext.java:234)
         at javax.security.auth.login.LoginContext.<init>(LoginContext.java:403)
         at sun.security.jgss.LoginUtility.login(LoginUtility.java:72)
         at sun.security.jgss.krb5.Krb5Util.getTicketFromSubject(Krb5Util.java:137)
         at sun.security.jgss.krb5.Krb5InitCredential$1.run(Krb5InitCredential.java:331)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.security.jgss.krb5.Krb5InitCredential.getTgtFromSubject(Krb5InitCredential.java:328)
         at sun.security.jgss.krb5.Krb5InitCredential.getInstance(Krb5InitCredential.java:131)
         at sun.security.jgss.krb5.Krb5MechFactory.getCredentialElement(Krb5MechFactory.java:72)
         at sun.security.jgss.GSSManagerImpl.getCredentialElement(GSSManagerImpl.java:149)
         at sun.security.jgss.GSSCredentialImpl.add(GSSCredentialImpl.java:389)
         at sun.security.jgss.GSSCredentialImpl.<init>(GSSCredentialImpl.java:60)
         at sun.security.jgss.GSSCredentialImpl.<init>(GSSCredentialImpl.java:37)
         at sun.security.jgss.GSSManagerImpl.createCredential(GSSManagerImpl.java:96)
         at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:178)
         at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:158)
         at com.sun.security.sasl.gsskerb.GssKrb5Client.evaluateChallenge(GssKrb5Client.java:155)
         at com.sun.jndi.ldap.sasl.LdapSasl.saslBind(LdapSasl.java:105)
         at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:214)
         at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2637)
         at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:283)
         at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
         at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
         at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
         at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:197)
         at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:82)
         at org.apache.catalina.realm.JNDIRealm.open(JNDIRealm.java:1515)
         at org.apache.catalina.realm.JNDIRealm.start(JNDIRealm.java:1601)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1004)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1012)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)
         at org.apache.catalina.core.StandardService.start(StandardService.java:450)
         at org.apache.catalina.core.StandardServer.start(StandardServer.java:683)
         at org.apache.catalina.startup.Catalina.start(Catalina.java:537)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:271)
         at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:409)
    Caused by: java.io.IOException: Unable to locate a login configuration
         at com.sun.security.auth.login.ConfigFile.init(ConfigFile.java:206)
         at com.sun.security.auth.login.ConfigFile.<init>(ConfigFile.java:95)
         ... 56 moreAm I moving in the right direction?
    -Dennis

  • Help with Payroll program

    Hello I need help with the following code for a Payroll program.
    //CheckPoint: Payroll Program Part 3
    //Java Programming IT215
    //Arianne Gallegos
    //05/02/2007
    //Payroll3.java
    //Payroll program that calculates the weekly pay for an employee.
    import java.util.Scanner; // program uses class Scanner
    public class Payroll3
         private string name;
         private double rate;
         private double hours;
         // Constructor to store Employee Data
         public EmployeeData( String nameOfEmployee, double hourlyRate, double hoursWorked )
              name = nameOfEmployee;
              rate = hourlyRate;
              hours = hoursWorked;
         } // end constructor
    } //end class EmployeeData
       // main method begins execution of java application
       public static void main( String args[] )
          System.out.println( "Welcome to the Payroll Program! " );
          boolean quit = false; // This flag will control whether we exit the loop below
          // Loop until user types "quit" as the employee name:
          while (!quit)
           // create scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.println();  // outputs a blank line
            System.out.print( "Please enter the employee name or quit to terminate program: " );
            // prompt for and input employee name
            String nameOfEmployee = input.nextLine(); // read what user has inputted
            if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
              System.out.println( "Program has ended" );
              quit = true;
    else
              // User did not indicate to stop, so continue reading info for this iteration:
              float hourlyRate; // first number to multiply
              float hoursWorked; // second number to multiply
              float product; // product of hourlyRate and hoursWorked
              System.out.print( "Enter hourly rate: " ); // prompt
              hourlyRate = input.nextFloat(); // read first number from user
              while (hourlyRate <= 0) // prompt until a positive value is entered
                 System.out.print( "Hourly rate must be a positive value. " +
                   "Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
                  hourlyRate = input.nextFloat(); // read first number again
              System.out.print( "Enter hours worked: " ); // prompt
              hoursWorked = input.nextFloat(); // read second number from user
              while (hoursWorked <= 0) // prompt until a positive value is entered
                 System.out.print( "Hours worked must be a positive value. " +
                   "Please enter the hours worked again: " ); // prompt for positive value for hours worked
                  hoursWorked = input.nextFloat(); // read second number again
              product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
              // Display output for this iteration
              System.out.println(); // outputs a blank line
              System.out.print( nameOfEmployee ); // display employee name
              System.out.printf( "'s weekly pay is: $%,.2f\n", product);  // display product
              System.out.println(); // outputs a blank line
          // Display ending message:
          System.out.println( "Thank you for using the Payroll program!" );
          System.out.println(); // outputs a blank line
       } // end method main
    } // end class Payroll3I am getting the following errors:
    Payroll3.java:18: invalid method declaration; return type required
    public EmployeeData( String nameOfEmployee, double hourlyRate, double hours
    Worked )
    ^
    Payroll3.java:28: class, interface, or enum expected
    public static void main( String args[] )
    ^
    Payroll3.java:33: class, interface, or enum expected
    boolean quit = false; // This flag will control whether we exit the loop b
    elow
    ^
    Payroll3.java:36: class, interface, or enum expected
    while (!quit)
    ^
    Payroll3.java:42: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:43: class, interface, or enum expected
    System.out.print( "Please enter the employee name or quit to terminate p
    rogram: " );
    ^
    Payroll3.java:45: class, interface, or enum expected
    String nameOfEmployee = input.nextLine(); // read what user has inputted
    ^
    Payroll3.java:48: class, interface, or enum expected
    if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
    uit program
    ^
    Payroll3.java:51: class, interface, or enum expected
    quit = true;
    ^
    Payroll3.java:52: class, interface, or enum expected
    ^
    Payroll3.java:57: class, interface, or enum expected
    float hoursWorked; // second number to multiply
    ^
    Payroll3.java:58: class, interface, or enum expected
    float product; // product of hourlyRate and hoursWorked
    ^
    Payroll3.java:60: class, interface, or enum expected
    System.out.print( "Enter hourly rate: " ); // prompt
    ^
    Payroll3.java:61: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number from user
    ^
    Payroll3.java:64: class, interface, or enum expected
    while (hourlyRate <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:68: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number again
    ^
    Payroll3.java:69: class, interface, or enum expected
    ^
    Payroll3.java:72: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number from user
    ^
    Payroll3.java:75: class, interface, or enum expected
    while (hoursWorked <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:79: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number again
    ^
    Payroll3.java:80: class, interface, or enum expected
    ^
    Payroll3.java:86: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:87: class, interface, or enum expected
    System.out.print( nameOfEmployee ); // display employee name
    ^
    Payroll3.java:88: class, interface, or enum expected
    System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
    product
    ^
    Payroll3.java:89: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:91: class, interface, or enum expected
    ^
    Payroll3.java:96: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:98: class, interface, or enum expected
    } // end method main
    ^
    The problem I am having is getting the constructor to work with the rest of the program can someone please point out to me how to correct this. I have read my textbook as well as tutorials but I just don't seem to get it right. Please help.
    P.S. I have never taken a programming class before so please be kind.

    Ok, I changed the name of the constructor:
    //CheckPoint: Payroll Program Part 3
    //Java Programming IT215
    //Arianne Gallegos
    //04/23/2007
    //Payroll3.java
    //Payroll program that calculates the weekly pay for an employee.
    import java.util.Scanner; // program uses class Scanner
    public class Payroll3
         private string name;
         private float rate;
         private float hours;
         // Constructor to store Employee Data
         public void Payroll3( string nameOfEmployee, float hourlyRate, float hoursWorked )
              name = nameOfEmployee;
              rate = hourlyRate;
              hours = hoursWorked;
         } // end constructor
    } //end class EmployeeData
       // main method begins execution of java application
       public static void main( String args[] )
          System.out.println( "Welcome to the Payroll Program! " );
          boolean quit = false; // This flag will control whether we exit the loop below
          // Loop until user types "quit" as the employee name:
          while (!quit)
           // create scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.println();  // outputs a blank line
            System.out.print( "Please enter the employee name or quit to terminate program: " );
            // prompt for and input employee name
            String nameOfEmployee = input.nextLine(); // read what user has inputted
            if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
              System.out.println( "Program has ended" );
              quit = true;
    else
              // User did not indicate to stop, so continue reading info for this iteration:
              float hourlyRate; // first number to multiply
              float hoursWorked; // second number to multiply
              float product; // product of hourlyRate and hoursWorked
              System.out.print( "Enter hourly rate: " ); // prompt
              hourlyRate = input.nextFloat(); // read first number from user
              while (hourlyRate <= 0) // prompt until a positive value is entered
                 System.out.print( "Hourly rate must be a positive value. " +
                   "Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
                  hourlyRate = input.nextFloat(); // read first number again
              System.out.print( "Enter hours worked: " ); // prompt
              hoursWorked = input.nextFloat(); // read second number from user
              while (hoursWorked <= 0) // prompt until a positive value is entered
                 System.out.print( "Hours worked must be a positive value. " +
                   "Please enter the hours worked again: " ); // prompt for positive value for hours worked
                  hoursWorked = input.nextFloat(); // read second number again
              product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
              // Display output for this iteration
              System.out.println(); // outputs a blank line
              System.out.print( nameOfEmployee ); // display employee name
              System.out.printf( "'s weekly pay is: $%,.2f\n", product);  // display product
              System.out.println(); // outputs a blank line
          // Display ending message:
          System.out.println( "Thank you for using the Payroll program!" );
          System.out.println(); // outputs a blank line
       } // end method main
    } // end class Payroll3I still get the following error codes:
    C:\IT215\Payroll3>javac Payroll3.java
    Payroll3.java:28: class, interface, or enum expected
    public static void main( String args[] )
    ^
    Payroll3.java:33: class, interface, or enum expected
    boolean quit = false; // This flag will control whether we exit the loop b
    elow
    ^
    Payroll3.java:36: class, interface, or enum expected
    while (!quit)
    ^
    Payroll3.java:42: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:43: class, interface, or enum expected
    System.out.print( "Please enter the employee name or quit to terminate p
    rogram: " );
    ^
    Payroll3.java:45: class, interface, or enum expected
    String nameOfEmployee = input.nextLine(); // read what user has inputted
    ^
    Payroll3.java:48: class, interface, or enum expected
    if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
    uit program
    ^
    Payroll3.java:51: class, interface, or enum expected
    quit = true;
    ^
    Payroll3.java:52: class, interface, or enum expected
    ^
    Payroll3.java:57: class, interface, or enum expected
    float hoursWorked; // second number to multiply
    ^
    Payroll3.java:58: class, interface, or enum expected
    float product; // product of hourlyRate and hoursWorked
    ^
    Payroll3.java:60: class, interface, or enum expected
    System.out.print( "Enter hourly rate: " ); // prompt
    ^
    Payroll3.java:61: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number from user
    ^
    Payroll3.java:64: class, interface, or enum expected
    while (hourlyRate <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:68: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number again
    ^
    Payroll3.java:69: class, interface, or enum expected
    ^
    Payroll3.java:72: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number from user
    ^
    Payroll3.java:75: class, interface, or enum expected
    while (hoursWorked <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:79: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number again
    ^
    Payroll3.java:80: class, interface, or enum expected
    ^
    Payroll3.java:86: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:87: class, interface, or enum expected
    System.out.print( nameOfEmployee ); // display employee name
    ^
    Payroll3.java:88: class, interface, or enum expected
    System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
    product
    ^
    Payroll3.java:89: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:91: class, interface, or enum expected
    ^
    Payroll3.java:96: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:98: class, interface, or enum expected
    } // end method main
    ^
    27 errors
    Any other suggestions?

  • Need Help With D&D Program

    Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
    I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
    1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
    The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
    The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
    I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
    Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
    My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
    One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
    This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
    Sorry for the length. Thanks for any help you can give.

    The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
    Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
         private static GraphicsConfiguration gConfig;
         private static Dimension compSize = new Dimension(80, 22);
         private static Image image = null;
         public static Image getImage(Class objectClass)
              if (gConfig == null)
                   GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
                   GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
                   gConfig = gDevice.getDefaultConfiguration();
              image = gConfig.createCompatibleImage(compSize.width, compSize.height);
              JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
              jc.setSize(compSize);
              Graphics g = image.getGraphics();
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, compSize.width, compSize.height);
              g.setColor(Color.BLACK);
              jc.paint(g);
              return image;
    }And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
         private static DragSource dragSource = DragSource.getDefaultDragSource();
         private static DragGestureListener dgl = new DragMoveGestureListener();
         private static TransferHandler th = new ObjectTransferHandler();
         private Class compClass;
         private Image image;
         Dragable(Class compClass)
              this.compClass = compClass;
              image = JComponentImage.getImage(compClass);
              setIcon(new ImageIcon(image));
              setTransferHandler(th);
              dragSource.createDefaultDragGestureRecognizer(this,
                                                          DnDConstants.ACTION_COPY,
                                                          dgl);
         public Class getCompClass()
              return compClass;
    }Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
         public static Object instantiate(Class objectClass)
              Object o = null;
              try
                   o = objectClass.newInstance();
              catch (Exception e)
                   System.out.println("ObjectFactory#instantiate: " + e);
              String name = objectClass.getName();
              int lastDot = name.lastIndexOf('.');
              name = name.substring(lastDot + 1);
              if (o instanceof JLabel)
                   ((JLabel)o).setText(name);
              if (o instanceof JButton)
                   ((JButton)o).setText(name);
              if (o instanceof JTextComponent)
                   ((JTextComponent)o).setText(name);
              return o;
    }Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
         private static DataFlavor df;
          * Constructor for ObjectTransferHandler.
         public ObjectTransferHandler() {
              super();
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   Debug.trace(e.toString());
         public Transferable createTransferable(JComponent jC) {
              Transferable t = null;
              try {
                   t = new ObjectTransferable(((Dragable) jC).getCompClass());
              } catch (Exception e) {
                   Debug.trace(e.toString());
              return t;
         public int getSourceActions(JComponent c) {
              return DnDConstants.ACTION_MOVE;
         public boolean canImport(JComponent comp, DataFlavor[] flavors) {
              if (!(comp instanceof Dragable) && flavors[0].equals(df))
                   return true;
              return false;
         public boolean importData(JComponent comp, Transferable t) {
              JComponent c = null;
              try {
                   c = (JComponent) t.getTransferData(df);
              } catch (Exception e) {
                   Debug.trace(e.toString());
              comp.add(c);
              comp.validate();
              return true;
    public class ObjectTransferable implements Transferable {
         private static DataFlavor df = null;
         private Class objectClass;
         ObjectTransferable(Class objectClass) {
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   System.out.println("ObjectTransferable: " + e);
              this.objectClass = objectClass;
          * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
         public DataFlavor[] getTransferDataFlavors() {
              return new DataFlavor[] { df };
          * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
         public boolean isDataFlavorSupported(DataFlavor testDF) {
              return testDF.equals(df);
          * @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
         public Object getTransferData(DataFlavor arg0)
              throws UnsupportedFlavorException, IOException {
              return ObjectFactory.instantiate(objectClass);
    }And of course the test class:public class DragAndDropTest extends JFrame
         JPanel leftPanel = new JPanel();
         JPanel rightPanel = new JPanel();
         Container contentPane = getContentPane();
         Dragable dragableJLabel;
         Dragable dragableJButton;
         Dragable dragableJTextField;
         Dragable dragableJTextArea;
          * Constructor DragAndDropTest.
          * @param title
         public DragAndDropTest(String title)
              super(title);
              dragableJLabel = new Dragable(JLabel.class);
              dragableJButton = new Dragable(JButton.class);
              dragableJTextField = new Dragable(JTextField.class);
              dragableJTextArea = new Dragable(JTextArea.class);
              leftPanel.setBorder(new EtchedBorder());
              BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
              leftPanel.setLayout(boxLay);
              leftPanel.add(dragableJLabel);
              leftPanel.add(dragableJButton);
              leftPanel.add(dragableJTextField);
              leftPanel.add(dragableJTextArea);
              rightPanel.setPreferredSize(new Dimension(500,500));
              rightPanel.setBorder(new EtchedBorder());
              rightPanel.setTransferHandler(new ObjectTransferHandler());
              contentPane.setLayout(new BorderLayout());
              contentPane.add(leftPanel, "West");
              contentPane.add(rightPanel, "Center");
         public static void main(String[] args)
              JFrame frame = new DragAndDropTest("Drag and Drop Test");
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    }I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
    Regards,
    Tim

  • Help with data access

    Hi,
    I am new to Java and stuck at a problem. Situation is like following-
    package X
    public abstract class A {
         A(int a) { this.a=p; }
         protected int p;
         abstract int func();
    package Y
    public class B extends A{
         B(int b) { super(b); }
         B() {}
         //p is accessible here
         int func() {
              D d=new D();
              d.func2();
        static void main() {
            func();
    public abstract class C extends B{
    public class D extends C implements interface{
         int func2() {}
    }Now my problem is when I try to access p from func2(), I am getting a NullPointerException error. I am not initialising p anywhere through D()'s and B()'s no argument constructor. Is that the problem?

    When you post code it doesn't help when the code doesn't actually reflect the problem.
    The code you posted isn't legal java so given that it won't even compile you certainly can't get a null pointer exception from that. And where you commented the usage of 'p' you can't use it there so that doesn't help with guessing what you actual code might have looked like.
    So all I can do is offer the following general advice.
    Null pointer exceptions occur because a reference is null and it is de-referenced.. Thus if you do a line like the following.
    xxx.p
    Then 'xxx' is the only possible thing that can be null.
    The stack trace of the exception will tell you the exact line that the problem occurred on.

  • Help with java coding involving stacks and queues.

    I was wondering if anyone can help with tips on what to fill in for the coding.
    My project is to creating a word processor by the process of 2 stacks. The methods are given, but I'm not really sure what goes in them. So I was wonder if anyone can answer this for me, or give tips that would be great thanks.
    Example Code, similar to what were suppose to do, but instead it's CHARACTER stacks rather than String.
    [http://www.cs.jhu.edu/~jason/226/hw3/source/EditableString.java]

    /** Stack of Characters to the left of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack left;
      /** Stack of Characters to the right of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack right;Do you know how a stack works?
    No - Google it
    Yes - Continue on with this post
    /** Another constructor.
       * @param left The text to the left of the cursor.
       * @param right The text to the right of the cursor.
      public EditableString(String left, String right) {
        // fill this in
      }Do you know how to read?
    No - How did you answer this question then?
    Yes - Then why can't you read the comments above each method. Is it really that hard to understand?
    Mel

  • HELP with object carousel

    Hi,
    I need some help with the use of the DSM-CC object carousel.
    In my Xlet, I need to read a file (previsioni.TXT), that is in the package testo; this is the structure of my folder:
    \\mio; the first package
    \\ MyXlet.java
    \\ testo; package with the text
    \\ previsioni.TXT
    1. so I create un object carousel and then access the file with the java.io.File :
    try {
                   System.out.println("Requesting file");
                        DSMCCObject carouselFile = new DSMCCObject("testo/previsioni.TXT");
              carouselFile.synchronousLoad();
              FileInputStream inFile = new FileInputStream(carouselFile);
              //Construct a DataInputStream by using the
                   //FileInputStream in the constructor method.
              DataInputStream inData = new DataInputStream (inFile);
              //Invoke methods of DataInputStream to read data from the data source.
         String s = inData.readUTF();
         System.out.println(s);
              //Close the FilterInputStream.
         inData.close ();
                   catch (InvalidPathNameException e) {
                        System.out.println("Invalid path name!");
                   catch (IOException e){
                        System.out.println("Problem reading previsioni.txt ");
    but when I run this code Xletview write
    [XleTView]-INFO->loading Xlet... [mio.StatiXlet]
    [XleTView]-INFO->XLET started... [mio.StatiXlet]
    mio.StatiXlet : Inizializzazione avvenuta!
    mio.StatiXlet : Hello TV World
    Requesting file
    xjava.io.File -
    Problem reading previsioni.txt
    and so there is an IO execption. Can someone help me?
    2. then, when the file is in the string s, i would display this file; I try with the Htext:
    texts = new HText( s, 20, 20, 200, 300, new Font("Tiresias", Font.BOLD, 26), Color.black, Color.white, new HDefaultTextLayoutManager());
    but when I compile the code appear:
    StatiXlet.java:173: cannot resolve symbol
    symbol : variable s
    location: class mio.StatiXlet
    texts = new HText( s, 20, 20, 200, 300, new Font("Tiresi
    as", Font.BOLD, 26), Color.black, Color.white, new HDefaultTextLayoutManager());
    ^
    1 error
    Do you know how can I display this file?
    Thank you very much

    Hi beker,
    thank you so much for your help, but I have another question.
    I use your code and when I compile is OK, but when I run it in XletView it doesn't find the file previsioni.TXT and write this:
    [XleTView]-INFO->loading Xlet... [mio.StatiXlet]
    [XleTView]-INFO->XLET started... [mio.StatiXlet]
    mio.StatiXlet : Inizializzazione avvenuta!
    mio.StatiXlet : Hello TV World
    xjava.io.File - testo/previsioni.TXT
    java.io.FileNotFoundException: E:\Documenti\tirocinio\xlet esempi\testo\previsio
    ni.TXT (Impossibile trovare il percorso specificato)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at xjava.io.FileInputStream.<init>(Unknown Source)
    at xjava.io.FileInputStream.<init>(Unknown Source)
    at mio.StatiXlet.startXlet(StatiXlet.java:97)
    at net.beiker.xletview.xlet.XletManager.resumeRequest(Unknown Source)
    at net.beiker.xletview.xlet.XletManager.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:536)
    s=not read
    What does it mean? I'm sure that the path is right, what do you think?
    Thank you very much beiker for your help

  • Help with database... plzzz

    Hi, I am trying to create a simple form in Java... What I am trying to do is enter a particular User ID and it should display all the information, regarding that userId... I am a starter.. Just trying to do some database stuffs.. I was wondering if anyone can help me with this without the help of JDBC.. thank you... So far I have created a form, textfield and buttons.. thats it..

    Thank for the help with the last problem, but now i am facing another one. The database and the forms works fine independently. But i cannot connect them, what i mean is if i click "insert" button to insert data into the database, the database window does not show up. i used the same code for the forms and it worked fine.. here is the code that i was using..
    private void xInsertRecordBtnMouseClicked(java.awt.event.MouseEvent evt) {                                             
            try
                this.setVisible(false);
                teamproject.EmployeeForm.class.newInstance().setVisible(true);
            } catch (InstantiationException ex)                                            
                Logger.getLogger(Main_Higher_Access.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex)
                Logger.getLogger(Main_Higher_Access.class.getName()).log(Level.SEVERE, null, ex);
            }I wonder if there is any other way to import the data from the database into the form. or.. to show the database..
    i am getting the following errors....
    Exception in thread "AWT-EventQueue-0" Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 9.1 (Build b36-rc)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.Error Code: -4499
            at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:289)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:87)
            at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:170)
            at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:537)
            at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:206)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:212)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:78)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:111)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:105)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:76)
            at teamproject.NewMasterDetailForm.initComponents(NewMasterDetailForm.java:29)
            at teamproject.NewMasterDetailForm.<init>(NewMasterDetailForm.java:14)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at java.lang.Class.newInstance0(Class.java:355)
            at java.lang.Class.newInstance(Class.java:308)
            at teamproject.Main_Higher_Access.xInsertRecordBtnMouseClicked(Main_Higher_Access.java:150)
            at teamproject.Main_Higher_Access.access$100(Main_Higher_Access.java:16)
            at teamproject.Main_Higher_Access$2.mouseClicked(Main_Higher_Access.java:52)
            at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3995)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
            at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
            at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
            at java.sql.DriverManager.getConnection(DriverManager.java:582)
            at java.sql.DriverManager.getConnection(DriverManager.java:154)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:85)
            ... 40 more
    Caused by: org.apache.derby.client.am.DisconnectException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
            at org.apache.derby.client.am.Connection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
            at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
            ... 44 more
    Caused by: java.net.ConnectException: Connection refused: connect
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
            at java.net.Socket.connect(Socket.java:519)
            at java.net.Socket.connect(Socket.java:469)
            at java.net.Socket.<init>(Socket.java:366)
            at java.net.Socket.<init>(Socket.java:179)
            at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            ... 50 more
    [TopLink Info]: 2007.12.05 12:04:07.281--ServerSession(16607409)--TopLink, version: Oracle TopLink Essentials - 9.1 (Build b36-rc)
    Exception in thread "AWT-EventQueue-0" Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 9.1 (Build b36-rc)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.Error Code: -4499
            at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:289)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:87)
            at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:170)
            at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:537)
            at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:206)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:212)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:78)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:111)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:105)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:76)
            at teamproject.NewMasterDetailForm.initComponents(NewMasterDetailForm.java:29)
            at teamproject.NewMasterDetailForm.<init>(NewMasterDetailForm.java:14)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at java.lang.Class.newInstance0(Class.java:355)
            at java.lang.Class.newInstance(Class.java:308)
            at teamproject.Main_Higher_Access.xInsertRecordBtnMouseClicked(Main_Higher_Access.java:150)
            at teamproject.Main_Higher_Access.access$100(Main_Higher_Access.java:16)
            at teamproject.Main_Higher_Access$2.mouseClicked(Main_Higher_Access.java:52)
            at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3995)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
            at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
            at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
            at java.sql.DriverManager.getConnection(DriverManager.java:582)
            at java.sql.DriverManager.getConnection(DriverManager.java:154)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:85)
            ... 40 more
    Caused by: org.apache.derby.client.am.DisconnectException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
            at org.apache.derby.client.am.Connection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
            at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
            ... 44 more
    Caused by: java.net.ConnectException: Connection refused: connect
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
            at java.net.Socket.connect(Socket.java:519)
            at java.net.Socket.connect(Socket.java:469)
            at java.net.Socket.<init>(Socket.java:366)
            at java.net.Socket.<init>(Socket.java:179)
            at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            ... 50 more
    [TopLink Info]: 2007.12.05 12:05:01.921--ServerSession(16607409)--TopLink, version: Oracle TopLink Essentials - 9.1 (Build b36-rc)
    Exception in thread "AWT-EventQueue-0" Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 9.1 (Build b36-rc)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.Error Code: -4499
            at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:289)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:87)
            at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:170)
            at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:537)
            at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:206)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:212)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:78)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:111)
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:105)
            at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:76)
            at teamproject.NewMasterDetailForm.initComponents(NewMasterDetailForm.java:29)
            at teamproject.NewMasterDetailForm.<init>(NewMasterDetailForm.java:14)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at java.lang.Class.newInstance0(Class.java:355)
            at java.lang.Class.newInstance(Class.java:308)
            at teamproject.Main_Higher_Access.xInsertRecordBtnMouseClicked(Main_Higher_Access.java:150)
            at teamproject.Main_Higher_Access.access$100(Main_Higher_Access.java:16)
            at teamproject.Main_Higher_Access$2.mouseClicked(Main_Higher_Access.java:52)
            at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3995)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.sql.SQLTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
            at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
            at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
            at java.sql.DriverManager.getConnection(DriverManager.java:582)
            at java.sql.DriverManager.getConnection(DriverManager.java:154)
            at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:85)
            ... 40 more
    Caused by: org.apache.derby.client.am.DisconnectException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
            at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
            at org.apache.derby.client.am.Connection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
            at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
            at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
            ... 44 more
    Caused by: java.net.ConnectException: Connection refused: connect
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
            at java.net.Socket.connect(Socket.java:519)
            at java.net.Socket.connect(Socket.java:469)
            at java.net.Socket.<init>(Socket.java:366)
            at java.net.Socket.<init>(Socket.java:179)
            at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)Edited by: saggu_baba on Dec 5, 2007 12:06 PM

Maybe you are looking for