Constructor question?

I am working on a class called Firm and it has an array of employee objects as its data field. Its constructor has an array of employee objects as its parameter: it initializes the data field array by copying references from the parameter array in a loop. Its main method creates one or two HourlyEmployee objects and one or more exemptEmployee objects. Then it calls setPay for one HourlyEmployee object and one ExemptEmployee objects and prints the results. Then it calls methods setPay and toString for these two objects (calling println, annotate this part of processing so that the output is readable).
What I have so far is, Employee being an abstract class that has a Constructor, and methods setPay(), getPay(), and toString. Subclasses HourlyEmployee and ExemptEmployee each with their own constructors and methods getPay() and setPay() along with toString() methods.
Currently this is what I have for code for my Firm class:
public class Firm
private Employee[] empObj;
Firm(Emp[] empObj)
for(int i = 0;i<empObj.length;++i)
arrObj=empObj;
}Does my constructor have an array of employee objects as its parameters? Do I need to create an Object array[] arrObj?

if Firm's constructor is being passed an Employee array, then just save that reference.
public class Firm
  private Employee[] empObj;
  public Firm(Emp[] empObj)
    this.empObj = empObj;
}Alternatively, you may wish to copy the parameter so that changes to the original (made outside by the guy who passed it to you, for example) don't affect it. In that case, change Firm's constructor to do this:
this.empObj = new Employee[empObj.length];
for (int i = 0; i < empObj.length; ++i)
  this.empObj[i] = empObj;
// or, you may even want to "deep-copy" it like this, if you created
// a "copy-constructor" or "clone" method:
this.empObj[i] = new Employee(empObj[i]);
//or
this.empObj[i] = (Employee) empObj[i].clone();

Similar Messages

  • Urgent constructor question..

    I'm trying to call this Flower class in another class called Garden, in which I created a new Flower by using a statement
    private Flower lastflower;
    and it's saying it cannot find the symbol - constructor Flower.
    Can anyone tell me why and help correct this problem?
    Below is the code for my Flower class.
    Any help is really appreciated, it's for my Java class!
    import objectdraw.*;
    import java.awt.*;
    * Write a description of class Flower here.
    * @author (your name)
    * @version (a version number or a date)
    public class Flower
        protected FilledOval dot;
        protected FilledRect stem;
        protected FilledOval petal1;
        protected FilledOval petal2;
        protected static final int boundary = 100;
        protected RandomIntGenerator colorGen =
                new RandomIntGenerator(0,255);
        protected Color petalColor;
        protected Boolean flowerContains=false;
        private DrawingCanvas canvas;
        public void changeColor(){
        dot = new FilledOval(150,150,15,15, canvas);
        dot.setColor(Color.YELLOW);
        petalColor = new Color(colorGen.nextValue(),
                                    colorGen.nextValue(),
                                    colorGen.nextValue());
        petal1.setColor(petalColor);
        petal2.setColor(petalColor);
        public void grow(Location point){
        stem = new FilledRect (dot.getX()+3, dot.getY()+10, 10, 10, canvas);
        stem.setColor(Color.GREEN);
        if (dot.getY()>boundary){
            dot.move(0,-4);
        else{
         petal1 = new FilledOval(dot.getX()-12, dot.getY()-25, 40,70,canvas);
         petal2 = new FilledOval(dot.getX()-25, dot.getY()-10, 70,40,canvas);
         dot.sendToFront();
         stem.sendToBack();
         petal1.setColor(petalColor);
         petal2.setColor(petalColor);
        public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
            else{
                return false;
    }

    I don't care how fucking urgent you think it is, it isn't to us. We will answer your question when and how we feel llike it. Have some manners and if you must, then bump your original post. Don't create another time wasting piece of cr&#97;p!

  • Constructor question - dealing with protected methods

    Hi all, I'm trying to run a protected method, got somewhere by making the class a subclass - but not too sure about where to put the constructor for a class I'm trying to use (IQRegister). Can anyone help and point me in the right direction as to what I did wrong?
    public class Registration extends IQRegister {
    //Create new instance of ConnectionBean
    ConnectionBean conBean = new ConnectionBean();
    InfoQueryBuilder iqb = new InfoQueryBuilder();
    InfoQuery iq;
    //IQRegisterBuilder iqRegb = new IQRegisterBuilder();
    public Registration( IQRegisterBuilder iqRegb ) {
    super( iqRegb );
    //This constructor needs to go somewhere that will work>>>>>>>>>>>>>>
    IQRegister iqReg = new IQRegister( iqRegb );
    public void regUser() {
    String server = JOptionPane.showInputDialog( "Enter Server address" );
    InetAddress inetaddress;
    try {
    conBean.connect( inetaddress = InetAddress.getByName( server ));
    catch( UnknownHostException unknownhostexception ) {
    Object aobj[] = {
    "Cancel", "OK"
    int i = JOptionPane.showOptionDialog(null, "Retry Server?", server +
    ": Not Responding", -1, 2, null, aobj, aobj[1]);
    if( i == 1 )
    regUser();
    System.out.println( "Cannot resolve " + server + ":" + unknownhostexception.toString ());
    return;
    catch( IOException ioexception ) {
    Object aobj1[] = {
    "Cancel", "OK"
    int j = JOptionPane.showOptionDialog( null, "Cannot Connect to:",
    server,-1, 2, null, aobj1, aobj1[1] );
    if( j == 1 )
    regUser();
    System.out.println( "Cannot connect " + server);
    return;
    System.out.println( "Registering User" );
    registrationProcess();
    public void registrationProcess () {
    try {
    //Need to getXMLNS packet method getXMLNS() is protected
    iqReg.getXMLNS();
    catch ( InstantiationException e ) {
    System.out.println( "Error in building Registration packet" );
    String username = JOptionPane.showInputDialog( "Enter: Username" );
    String password = JOptionPane.showInputDialog( "Enter: Password" );
    ERROR:
    Registration.java:108: cannot resolve symbol
    symbol : variable iqReg
    location: class Registration
    iqReg.getXMLNS();
    ^
    1 error
    Thanks again :)

    Made some changes to code but getting some varied error here:
    Registration.java:31: <identifier> expected
    iqReg = new IQRegister( iqRegb );
    ^
    Registration.java:31: cannot resolve symbol
    symbol : class iqReg
    location: class Registration
    iqReg = new IQRegister( iqRegb );
    ^
    Registration.java:104: cannot resolve symbol
    symbol : variable iqReg
    location: class Registration
    iqReg.getXMLNS();
    ^
    3 errors
    CODE:
    public class Registration extends IQRegister {
    //Create new instance of ConnectionBean
    ConnectionBean conBean = new ConnectionBean();
    InfoQueryBuilder iqb = new InfoQueryBuilder();
    InfoQuery iq;
    //IQRegisterBuilder iqRegb = new IQRegisterBuilder();
    //This constructor problem here>>>>>>>>>>>>
    iqReg = new IQRegister( iqRegb );
    public Registration( IQRegisterBuilder iqRegb ) {
    super( iqRegb );
    .......same code..... as above....
    Thank you so much for the guidance..

  • Overloading constructor question

    The following douse not seem to work:-
    class A {
         A( int i ) {
              System.out.println( "A constructor" + i );
    class B {
         B( int i ) {
              System.out.println( "B constructor" + i );
    class C extends A {
         C () { // line 17
              System.out.println( "C constructor" );
         public static void main( String[] args ) {
              C c = new C();
    It complaines at line 17
    A(int) in A cannot be applied to ()
    C () {
    ^
    This has totaly bafeld be. I thought it was OK to add overloaded constructors in inheratid classes but it seems to be complaining that I am replacing C(int) wit C(), i.e. the constructor in the subclass has diferent arguments. surly this should simply add an overloaded constructer?
    Ben

    The first statement in every constructor must be a call to either a) another constructor in that class or b) a constructor of the super class. If you do not specify a call to either, then the compiler automatically will insert a call to the no argument constructor of the super class. Since there isn't a no-arg constructor in A, the compiler complains that you are calling the A(int) constructor with no arguments. You need to either add a no argument constructor to A, or you need to call the A(int) constructor from the C constructor with some default value.
    In case you didn't know, to call a super constructor from a subclass, you use the super keyword.
    Example:
    class A {
        A(int i) {}
    class B extends A {
        B() {
            super(2);  //This call the A(int) constructor.
    }

  • Constructor question.Help!

    Hi,
    I need help!I've been trying to do this for several hours now.
    My program takes in parameters a file cellSig.txt and a int in the main program and the int gives the number of for loops that need to be run.Now in the for loop,I have a constructor for class ranData.
    for(int model = 0;model<= cross; model++){
    ranData objData = new ranData(filename);
    }//cross is the parameter int given by user
    ranData basically takes the main file cellSig.txt and randomises and divides into 2 other files.It is vital that there should be different files for every 'for' loop.
    However I compile and
    ./ranData.java:5: illegal start of type
    try{
    ^
    ./ranData.java:40: <identifier> expected
    ^
    keyInput.java:18: cannot resolve symbol
    symbol : constructor ranData (java.lang.String)
    location: class ranData
    ranData objData = new ranData(filename);
    I'm posting the ranData.java code below.Pls help..I'm not sure what is wrong.
    import java.io.*;
    import java.util.*;
    public class ranData{
         ArrayList list = new ArrayList();
         try{
         BufferedReader in = new BufferedReader(new FileReader(filename));
         String FileToRead = in.readLine();
         while(FileToRead!= null){
              list.add(FileToRead);
              FileToRead = in.readLine();
         in.close();
         in = null;
         Collections.shuffle(list);
         List trainList = list.subList(0,2000);
         List testList = list.subList(2000,list.size());
         BufferedWriter  objBW =  new BufferedWriter(new FileWriter("cellSig.names"));
         BufferedWriter  objBWt =  new BufferedWriter(new FileWriter("cellSig.names"));
         Iterator x = trainList.iterator();
         Iterator y = testList.iterator();
         String tmp = "";
         String temp = "";
         while(x.hasNext()){
              tmp =(String) x.next() ;
              objBW.write(tmp);
              objBW.newLine();
         while(y.hasNext()){
              temp = (String)y.next() ;
              objBWt.write(temp);
              objBWt.newLine();
         objBW.close();
         objBWt.close();
         objBW = objBWt = null;
         x = y = null;
         }catch(IOException e){
         System.out.println(e);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    public RanData(String filename){     
         Filename = filename;
         try{
         BufferedReader in = new BufferedReader(new FileReader(Filename));
         String FileToRead = in.readLine();You are closing the constructor and start coding again without declaring the try catch within a method. Try this:
    import java.io.*;
    import java.util.*;
    public class RanData{
         ArrayList list = new ArrayList();
         public String Filename;
         public RanData(String filename){     
         Filename = filename;
         try{
         BufferedReader in = new BufferedReader(new FileReader(Filename));
         String FileToRead = in.readLine();
         while(FileToRead!= null){
              list.add(FileToRead);
              FileToRead = in.readLine();
         in.close();
         in = null;
         Collections.shuffle(list);
         List trainList = list.subList(0,2000);
         List testList = list.subList(2000,list.size());
         BufferedWriter  objBW =  new BufferedWriter(new FileWriter("cellSig.names"));
         BufferedWriter  objBWt =  new BufferedWriter(new FileWriter("cellSig.names"));
         Iterator x = trainList.iterator();
         Iterator y = testList.iterator();
         String tmp = "";
         String temp = "";
         while(x.hasNext()){
              tmp =(String) x.next() ;
              objBW.write(tmp);
              objBW.newLine();
         while(y.hasNext()){
              temp = (String)y.next() ;
              objBWt.write(temp);
              objBWt.newLine();
         objBW.close();
         objBWt.close();
         objBW = objBWt = null;
         x = y = null;
         }catch(IOException e){
         System.out.println(e);
    }I also reccomend you to read a good Java beginners books

  • Inheritance constructor question

    Hi
    I am having trouble understanding how the superclasses constructor works in inheritance:
    Please look at the following code:
    public class mySuperClass
         mySuperClass ()
              System.out.println("super1");
    public class myClass extends mySuperClass
         myClass ()
              System.out.println("hello1");
         myClass (int q)
              System.out.println("hello2");
    public static void main(String[] args)
              myClass o = new myClass ();
              myClass o = new myClass (3);
    When I run this program the console results are:
    super1
    hello1
    super1
    hello2
    Why does the constructor of the super class run even when I overload it?
    Thanks
    Aharon

    I think you meant to write "Why does the constructor of the super class run even when I overrideit?"
    And the point is you can't override a constructor (technically, they are not even methods). A constructor in a derived class (MyClass) must call a constructor in its superclass (MySuperClass ). If you do not explicitly call one:
    MyClass (int q) {
        super(...arguments...); // <---
        System.out.println("hello2");
    }There will be an attempt to implicitly to invoke super();

  • AIA FP 11g - Service Constructor Question

    Hi All,
    I am trying to create the Provider ABCS impl using the Service Constructor. I have defined the Solution Service Component in the AIA Project Lifecycle Workbench as BAERP Create Purchase Order List Ebiz Provider ABCS. The CreatePurchaseOrderList method of the PurchaseOrderEBS will invoke this ABCS with a list of Purchase Orders.
    To create the Service Contructor, these are the steps that I follow,
    1. Create New Project -> Business Tier -> AIA -> AIA Service Component Project
    2. Service Description: Select the Solution Service Component from the AIA Project Lifecycle Workbench
    3. Service Details: Product Code: Ebiz, Application Name: Ebiz, Application Id: EBIZ_01, Application Short Name: Ebiz, Service Operation: Create, Service Type: Provider ABCS ( Only relevant attributes are given)
    4. Service Object: WSDL: Select PurchaseOrderEBSV1.wsdl from EnterpriseBusinessServiceLibrary, Operations: CreatePurchaseOrderList
    5. Target Service Details: I am selecting the wsdl of a deployed composite, which inserts a list of Purchase Orders into a database, Operations: Process
    6. I click Finish - The ABCS as well as the BPEL process that gets created is CreatePurchaseOrderEbizProvABCSImpl, where as I was expecting it to be created as CreatePurchaseOrderListEbizProvABCSImpl.
    Did I miss something here, or should I be referring to the ABCS as CreatePurchaseOrderEbizProvABCSImpl?
    Regards,
    Anish.

    Hi,
    Check the Object Name field in Step 4 of Service Constructor. Ensure it is PurchaseOrderList, If it was jus PurchaseOrder you edit and append List to it.
    After Finish, your Prov ABCS will be named as CreatePurchaseOrderListEbizProvABCSImpl.
    Regards,
    Rahul

  • Distribution Constructor Questions

    Has anyone out there successfully incorporated custom scripts into the distribution constructor? What I'd like to to is to be able to incorporate arbitrary files into the image so that any boxes installed with my new image will have these files available at first boot. There is a lot of documentation on including custom scripts into the constructor but no good examples of the scripts themselves.
    Edited by: carsonoid on Dec 27, 2012 2:43 PM

    Just as an FYI, here is how I managed to accomplish my goal.
    Goal:
    To include some files/packages in a default installation of Solaris 11.1 using only the disk. The custom files and packages should not be dependent on any networked repository.
    Solution:
    1. Create a local (empty) repo on the machine that will be running the distribution constructor
    `pkgrepo create /export/repoSolaris11`
    2. Create a simple IPS package containing the files and publish it to the local repo
    http://docs.oracle.com/cd/E26502_01/html/E21383/pkgcreate.html#scrolltoc
    3. Create a new checkpoint in your distribution constructor xml manifest that points to a custom script.
    4. The custom script should copy the /export/repoSolaris11 folder to the root of the /rpool/dc/ai/build_data/boot_archive/ folder
    5. Run the distribution constructor and build a new .iso
    The iso should have a more or less standard layout except you will have a local filesystem repo available to the installation enviroment.
    6. Create a custom ai_manifest(5) file which includes an additional publisher entry at the top for your local filesystem repo. It should also include the custom packages for your repo:
    Ex:
    <publisher name="PUBNAMEHERE">
    <origin name="file:///repoSolaris11/"/>
    </publisher>
    Package list:
    <software_data action="install">
    <name>pkg:/[email protected]</name>
    <name>pkg:/group/system/solaris-large-server</name>
    <!-- Install custom packages, they should come from the local fileysystem repo -->
    <name>pkg:/tokyocabinet</name>
    <name>pkg:/cfengine</name>
    </software_data>
    That's it! When you do the automated install it will install the custom packages from a repo contained on the iso itself. The instructions aren't 100% but it should help anyone else with this know the right direction.
    One big caveat here is that the entire boot environment is loaded into a ramdisk. So make sure that your server has more ram than the repo's final size.
    Edited by: carsonoid on Jan 3, 2013 10:09 AM

  • Constructor questions

    What exactly does the gcd do in the following code? Does it mean that the constructor will call the gcd function whenever I make a constructor?
    Does it also mean that all values passed to Class Fraction will operate gcd before they're assigned to the instance variable?
    Thank you .
    public class Fraction {
        // Data Fields 
        private int numer;  // numerator of the fraction
        private int denom;  // denominator of the fraction
        // Constructors
        // Constructs a fraction mathematically equal to num/den.
        // The resulting fraction is reduced and has positive denominator.
        public Fraction(int num, int den) {
            int g = gcd(num, den);
            if (den < 0) {
                numer = -num/g;
                denom = -den/g;
            else {
                numer = num/g;
                denom = den/g;
         }

    What exactly does the gcd do in the following code?
    Does it mean that the constructor will call the gcd
    function whenever I make a constructor?
    Does it also mean that all values passed to Class
    Fraction will operate gcd before they're assigned to
    the instance variable?
    Thank you .
    public class Fraction {
    // Data Fields 
    private int numer;  // numerator of the fraction
    private int denom;  // denominator of the
    the fraction
    // Constructors
    // Constructs a fraction mathematically equal to
    l to num/den.
    // The resulting fraction is reduced and has
    has positive denominator.
    public Fraction(int num, int den) {
    int g = gcd(num, den);
    if (den < 0) {
    numer = -num/g;
    denom = -den/g;
    else {
    numer = num/g;
    denom = den/g;
    It means that every time you do a Fraction myFraction = new Fraction( 1, 3 ); that the gcd method will be called to caculate the gcd, which is used to set the value of the instance variables numer and denom.
    Without additional code, I can't tell you if it is used elsewhere in the fraction class, other than the constructor.
    RD-R
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Who wants to be a Millionaire ??? CODE???

    hi
    i'm tryin to make a basic game who wants to be a millionaire...i got the following..layout of the textfield textarea etc.. but i cant seem to use the vectors to store the questions from a txt file then transfer it over to the textarea box or radio buttons.... n how about the checking part??
    anyone know where to find help or can help me??
    thnks

    That is the game frame:
    // File:          GameFrame.java
    // Purpose:          The window that appears when the player chooses to play the game
    //                    This window shows the questions and answers and the amount being played for
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    import java.io.*;
    public class GameFrame extends JFrame implements ActionListener {
         private MainFrame frmMain;
         private Vector questionVector;
         private JTextField jtfquestions;
         private JButton btnCancel, btnPrevious, btnNext, btnSelect,btnStart;
         private JRadioButton jrba, jrbb, jrbc, jrbd;
         private ButtonGroup btg = new ButtonGroup();
         private JList score;
         private final String money []= {"15. 1000000","14. 500000","13. 250000","12. 125000","11. 64000","10. 32000","9. 16000","8. 8000","7. 4000","6. 2000","5. 1000","4. 500","3. 300","2. 200","1. 100"} ;
         public GameFrame(MainFrame mf)
         frmMain = mf;                    // Get a handle on caller
    score=new JList (money);
    score.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         JPanel p1=new JPanel();
         ImageIcon logo=new ImageIcon ("millionaire.jpg");
         p1.add(new JLabel(logo));
         JPanel p2=new JPanel();     
                         p2.add(score);
            JPanel p5=new JPanel();
           p5.setLayout(new GridLayout(2,3,4,4));
    p5.add(jrba = new JRadioButton("A", false));
    p5.add(jrbb = new JRadioButton("B", false));
    p5.add(jrbc = new JRadioButton("C", false));
    p5.add(jrbd = new JRadioButton("D", false));
    btg.add(jrba);
    btg.add(jrbb);
    btg.add(jrbc);
    btg.add(jrbd);
    JPanel p3=new JPanel();
    p3.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
    p3.add(jtfquestions=new JTextField(50));
    p3.add(p5);
    JPanel p4=new JPanel();
       p4.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
    p4.add(btnCancel=new JButton("Cancel"));
    p4.add(btnPrevious=new JButton("Previous"));
    p4.add(btnNext=new JButton("Next"));
    p4.add(btnSelect=new JButton("Select"));
    p4.add(btnStart=new JButton("START"));
    getContentPane().setLayout(new BorderLayout(5,5));
    getContentPane().add(p1, BorderLayout.NORTH);
    getContentPane().add(p2, BorderLayout.EAST);
    getContentPane().add(p3, BorderLayout.CENTER);
    getContentPane().add(p4, BorderLayout.SOUTH);
    Container cn = this.getContentPane();
    btnCancel.addActionListener(this);
    btnPrevious.addActionListener(this);
    btnStart.addActionListener(this);
    btnNext.addActionListener(this);
    jrba.addActionListener(this);
    jrbb.addActionListener(this);
    jrbc.addActionListener(this);
    jrbd.addActionListener(this);
    try
    readFile("questions.dat");     
    catch (Exception e)
         System.out.println(e);
    public void actionPerformed(ActionEvent e)
    public void readFile(String fileName) throws IOException
              BufferedReader bReader;
              String question;
              questionVector = new Vector();
              File inFile = new File(fileName);
              if (!inFile.exists())
              System.out.println("File does not exist");
                   //System.exit(0);
         bReader = new BufferedReader(new FileReader(inFile));
         question = bReader.readLine();
         while (question != null)
         String a1, a2, a3, a4, correct;
              int iCorrect;
              a1 = bReader.readLine();
              a2 = bReader.readLine();
              a3 = bReader.readLine();
              a4 = bReader.readLine();
         correct = bReader.readLine();
         // Convert the value from a string to an integer
         iCorrect=Integer.parseInt(correct);
                         // Create a new Question object using the parameterised constructor
    Question q = new Question(question,a1,a2,a3,a4,iCorrect);
         questionVector.add(q);
         question = bReader.readLine();
    // Close the file stream once we have finished reading the file
         bReader.close();     
    public void setQuestion(int questNum)
    Question q = (Question) questionVector.get(questNum);
    System.out.println("Question number "+questNum+ " is "+q.getQuestion());     
    public void showQuestions()
    for (int i=0; i< questionVector.size(); i++)
         // Cast the object stored in the Vector to type Question
    Question q = (Question)questionVector.elementAt(i);
                   q.printAll();
    Now Question Frame:
    // File:          Question.java
    // Purpose:          A Java class to store a question and possible answers
    public class Question
         private String question;
         private String answer1, answer2, answer3, answer4;
         private int correctAnswer=0;
    public Question()     
    public Question(String quest, String ans1, String ans2, String ans3, String ans4, int correct)
         question = quest;
         answer1=ans1;
         answer2=ans2;
         answer3=ans3;
         answer4=ans4;
         correctAnswer=correct;          
    public void printAll()
    System.out.println(question);
    System.out.println("A: " + answer1);
    System.out.println("B: " + answer2);
    System.out.println("C: " + answer3);
    System.out.println("D: " + answer4);
    System.out.println("Correct answer is answer number "+ correctAnswer);
    public String getQuestion()
                 return question;
    ok those are the codes now the hard part is making the question appear on the _private JTextField jtfquestions;_ n then having the ans place on the _private JRadioButton jrba, jrbb, jrbc, jrbd;_ then if a correct ans is inputed the JList score should move up like the game itself
    this is what it looks like GUI wise
    http://img164.imageshack.us/img164/6126/gui6iz.jpg
    now anyone have any tips or help options?
    thnks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Errors in Program

    I am currently trying to do a program but when I try to compile it I always get the same error. I have tried to correct the error without success. Below is the error and I shall post the code also. Any help would be greatly appreciated.
    LayoutGUI.java:71: cannot resolve symbol
    symbol : constructor Question (java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)
    location: class Question
                             theQuestions[totalQuestions] = new Question(question, choice[0], choice[1], choice[2], choice[3], correctAnswer);
    ^
    1 error

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class LayoutGUI extends CloseableFrame implements ActionListener
         private final int MAX_SIZE = 20;
         private final int SIZE = 20;
         private int total = 0;
         private JButton startButton;
         private JTextField questionField;
         private JTextField answersField;
         private JComboBox answerSelection;
         private JButton submitButton;
         private JTextField resultsField;
         int correctAnswers = 0;
         protected Question[] theQuestions = new Question[MAX_SIZE];
         public LayoutGUI()
              boolean done;
              String question;
              String[] choice = new String[4];
              String correctAnswer;
              int total = 0;
              int totalQuestions = 0;
              String TEXT_FILE = "questions.txt";          
              // question descriptions from file
              // open BufferedReader connection to text file
              File file = new File(TEXT_FILE);
              BufferedReader in = null;
              try
                   in = new BufferedReader(new FileReader(file));
              catch (FileNotFoundException e)
                   System.err.println("Error opening text file, file not found!");
                   System.exit(1);
              // read next question description (repeat the following
              // as often as necesary to process all text content)
              done = false;
              while (!done)
                   try
                        question = in.readLine();
                        choice[0] = in.readLine();
                        choice[1] = in.readLine();
                        choice[2] = in.readLine();
                        choice[3] = in.readLine();
                        correctAnswer = in.readLine();
                        if (question==null || choice[0]==null || choice[1]==null || choice[2]==null || choice[3]==null || correctAnswer==null)
                             done = true;
                        else
                             theQuestions[totalQuestions] = new Question(question, choice[0], choice[1], choice[2], choice[3], correctAnswer);
                             totalQuestions++;
                   catch(IOException ioex)
                        System.err.println("problem reading text file");
                        ioex.printStackTrace();
                        System.exit(1);
              try
                   in.close();
              catch(IOException ioex)
                   System.err.println("problem closing text file");
                   ioex.printStackTrace();
                   System.exit(1);
              // end of reading text file
              competenceTestLayout customLayout = new competenceTestLayout();
              getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
              getContentPane().setLayout(customLayout);
              // component 0
              startButton = new JButton("Start");
              getContentPane().add(startButton);
              //component 1
              questionField = new JTextField("");
              getContentPane().add(questionField);
              // component 2
              answersField = new JTextField("");
              getContentPane().add(answersField);
              // component 3
              answerSelection = new JComboBox();
              answerSelection.addItem("A");
              answerSelection.addItem("B");
              answerSelection.addItem("C");
              answerSelection.addItem("D");
              getContentPane().add(answerSelection);
              // component 4
              submitButton = new JButton("Submit");
              getContentPane().add(submitButton);
              // component 5
              resultsField = new JTextField("");
              getContentPane().add(resultsField);
              startButton.addActionListener(this);
              submitButton.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              if (source == startButton)
                   correctAnswers = 0;
                   // clear all fields
                   questionField.setText("");
                   answersField.setText("");
                   resultsField.setText("");
                   // choose the questions which the user will be asked
                   HashSet randomNos = new HashSet();
                   while (randomNos.size() < 10)
                        int n = (int)(Math.random() * SIZE);
                        randomNos.add(new Integer(n));
                   // now display the questions and answers
                   Iterator i = randomNos.iterator();
                   while (i.hasNext())
                        int n = ((Integer)(i.next())).intValue();
                        //questionField.append("" + n);
                        //questionField.setText(question);
                        System.out.println("random number = " + n);
              if (source == submitButton)
                   questionField.setText("Submit button pressed");
         class competenceTestLayout implements LayoutManager
              public competenceTestLayout()
              public void addLayoutComponent(String name, Component comp)
              public void removeLayoutComponent(Component comp)
              public Dimension preferredLayoutSize(Container parent)
                   Dimension dim = new Dimension(0,0);
                   Insets insets = parent.getInsets();
                   dim.width = 719 + insets.left + insets.right;
                   dim.height = 589 + insets.top + insets.bottom;
                   return dim;
              public Dimension minimumLayoutSize(Container parent)
                   Dimension dim = new Dimension(0,0);
                   return dim;
              public void layoutContainer(Container parent)
                   Insets insets = parent.getInsets();
                   Component c;
                   c = parent.getComponent(0);
                   if (c.isVisible()){c.setBounds(insets.left+296,insets.top+8,72,24);}
                   c = parent.getComponent(1);
                   if (c.isVisible()){c.setBounds(insets.left+8, insets.top+56,584,32);}
                   c = parent.getComponent(2);
                   if (c.isVisible()){c.setBounds(insets.left+8,insets.top+96,240,176);}
                   c = parent.getComponent(3);
                   if (c.isVisible()){c.setBounds(insets.left+304,insets.top+248,72,24);}
                   c = parent.getComponent(4);
                   if (c.isVisible()){c.setBounds(insets.left+440,insets.top+248,128,24);}
                   c = parent.getComponent(5);
                   if (c.isVisible()){c.setBounds(insets.left+8,insets.top+352,680,184);}
    }

  • Questions on Constructor

    Hello all:
    I have some doubts on constuctor. Can someone highlight to me?
    1) Can I put a constructor in another class?
    For example, I have a class, named Interact, which display a panel and some buttons. And another class is call Box. Third class is named Tools. My aim is that when I click the buttons of Interact class, it will invoke some actions accordingly, such as generate a new object of Box or Tools class, or call some methods of Box or Tool class.
    Is it necessary to place the constructor of Box and Tools class inside the Interact class? So that can make a handler of these two classes by calling the constructors. Hence to use the handler to call the methods of Box and Tools classes.
    I really hate to put a Box constructor inside a class other than Box class. Is there any alternative?
    2)Say I have two methods in Box class. One is named "public static double getBoxSize()" in Box class. Another method is named "public doulbe getBoxNumber()". Now I want to call these two methods by click a button in Interact Class. Is it true that I must call the first method with an object name of Box Class. Say"
    Box1.getBoxNumber()" ? And for the second method, I don't have to do so because the absence of "static" in the method header? Can I simply call this method by the statement " Box getBoxNumber" ?
    3)Lastly, I am really blur about the concept of class handler. According to my teacher's word, class handler is an object of Box class which generated by Interact class. We can communicate between Box class and Interact class by the use of class handler, for example Box1. But as for my understanding, we can do without handler if we declare all methods in Box class in the same way as getBoxNumber() method. " public double getBoxNumber()". By doing so, we can call all the methods in Box class without using a Box class object.
    Subconcious tell me that my concept is wrong somewhere. But I don't really see what is the point of using a handler. In fact, I don't quite understand what is a handler. Can someone clear my doubts?
    Thanks.

    Hello,
    To answer all your questions, I have to write a small article :-)
    1)You can not define a constructor of a class in another class.
    2)You can call methods of an object in any order. But it's upto your application design how you want to invoke them. To call static methods you don't need an instance of a class. It's opposite of instance methods.
    3)I think what you mean by handler is an object reference. Object reference is just a pointer(address) to the actual object.

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • Anyone heard of static Constructor? Pure Concept Question

    Hi All,
    I guess this is a little obscure but let me ask this anyway.
    Has anyone heard about a "static constructor"? No I am not talking about a static block in your code. I am talking about a static method which will be called every time you make a static call on a particular class. Just like the constructor gets called every time you create an Object. The difference will be that the static code will be executed only once while the static constructor will be called every time you call a static method.
    My question: Do you see a need, from the experience you have got, about such a construct being a feature of a language? I was talking to some people of a very well known company - who were telling me about this special feature - as they put it - being part of their Proprietary language. They couldn't convince me as to why this "special" feature was required. I seek help from the Community to help me think about this. I tried seeking an answer to this question on the net but to no avail.
    I for one, am not going to stop my quest after posting here - but I would be grateful if any of you could help me.
    Thanks for all your support.
    Best Regards,
    Manish

    Hi All,
    I am overwhelmed by the response. Thanks for spending your time thinking about this.
    Some of the questions you asked were...
    teknologikl : Did the people say about how is it useful?
    javax.pert : No. They tried to tell me things like initializing static objects which I could have as well done in a common method which I call in the start of every static method. Basically they could not convince me about the use of a static constructor. May be they did not know too well why it was put in the first place. Because I was talking to programmers rather than Designers. But I did not want to stop at that. I wanted to tickle my gray cells and yours to find out why would someone put this as part of a language? I agree with most of your posts but instead of telling me that this is not going to be very useful ( which I already thought of), I would appreciate if you can help me think Why would someone have put it at all. You see what I am saying?
    rjwr: static factory methods
    javax.pert: Yup. I am aware and use static factory methods. But this is a little different. This is called automatically by the VM - just like a normal constructor - whenever a static method is called.
    dubwai: This sounds pretty lame to me...
    javax.pert: Sorry if I wasted your time. But please look at my response to teknologikl above.
    DrClap:
    javax.pert: Yup, yup. I thought just the way you are saying. I am actually trying to get in touch with some one who knows more about this proprietary language - maybe one of the designers. I would be glad to share the findings when it comes - if it is worth sharing of course. Thanks for your time though. :)
    rvflannery: Security framework.
    javax.pert: True. I agree with you about this being a wrapper for security purposes. Maybe this is what they thought of. One reason I see is that because they expose the APIs to third party vendors. These APIs can talk, by extending certain objects, to the sensitive areas of the database. I guess this could be one of the reasons. I will share it once I know more about it.
    trejkaz: For debugging.
    javax.pert: See my answer to rvflannery above.
    Thanks all of you for spending your time with me. I will keep you informed whenever I get something worth sharing.
    Thanks again,
    Best Regards,
    Manish

  • Some question about constructor

    The code below shows some of the text for a class called City. As you can see, a City has two instance variables, name and population. Write a complete public constructor (including header line) with no parameters, which sets the population to an initial value of -1, and the name to an initial value of "unknown".
    this is the question:
    this is what I wrote:
    public class City {
      private String name;
      private int population;
    public City(String n, int p){
      name = n;
      population = p;
    public City(){
      name = "unknown";
      population = -1;
    } y is it wrong?

    Umass wrote:
    The code below shows some of the text for a class called City. As you can see, a City has two instance variables, name and population. Write a complete public constructor (including header line) with no parameters, which sets the population to an initial value of -1, and the name to an initial value of "unknown".
    this is the question:
    this is what I wrote:
    public class City {
    private String name;
    private int population;
    public City(String n, int p){
    name = n;
    population = p;
    public City(){
    name = "unknown";
    population = -1;
    } y is it wrong?The comment about the missing closing brace appears to be correct. It would help if you'd post the compiler message instead of just telling us that it's "wrong". More info, please.
    The code you posted isn't wrong, once you make that correction, but it's not the way I'd write it.
    Here's what I would do:
    public class City
        private static final String DEFAULT_NAME = "unknown";
        private static final int DEFAULT_POPULATION = 0;
        private String name;
        private int population;
        public City()
            this(DEFAULT_NAME, DEFAULT_POPULATION);
        public City(String name, int population)
            setName(name);
            setPopulation(population);
        private void setName(String name)
            if (name == null)
                throw new IllegalArgumentException("name cannot be null");
            this.name = name;
        private void setPopulation(int population)
            if (population < 0)
                throw new IllegalArgumentException("population cannot be negative");
            this.population = population;
    }Here's why:
    (1) No magic constants. I like having static final constants with a name that spells out what it's for. Better than comments, no ambiguity for users. A negative population makes no sense to me, but zero does.
    (2) Objects should be fully initialized and ready to go. Write one constructor that fully initializes the object, every attribute. I like to do it with setters, because I can embed any rules for sensible values there. They protect both the constructor and any public setters that I might have without duplicating code. I made the setters private because I didn't want my City to be mutable.
    (3) Have your default constructor call the full constructor. It makes clear what the default values are (in javadocs, preferrably).
    %

Maybe you are looking for

  • Applet edit form option don't works in J Dev 11g

    We want to develop an applet ADF apllication . We drop adf view to the screen . chosee ADF edit. But ADF edit from option not works correctly... notinh happen.

  • Adobe Reader XI 11.0.07 : Internal Error Occurred

    I get Internal error occurred message every time I try to run Adobe Reader XI 11.0.07, after further investigation I discovered that the only way to run it is to run it as admin, but I have other  users who uses the same virtual machine and they are

  • Long time starting up

    When I start up I get the blank blue screen for at least 5 minutes.  This is only in OS.X. I use OS.9 often still and don't get any problem starting up in that. I do get this issue when changing Start Up Disk from OS.9 to OS.X. They are on the same h

  • WRT54G lost wifi

    Hi, My WRT54G lost the wifi connection. I can get the internet if I connect the cable from my modem to my computer but my wireless connection is gone. So it's an issue with the router or settings. I called Linksys and was told the settings would have

  • My credit-I had +£6.00 in my UK account and as I a...

    Dear Sir/Ms.,                I have account with you for along time in London England. It's been a while since I used your sevices. The last time I used to call,I had a credit of £6.00+. I am in USA and trying to use Skype,I been asked to pay again.