Constructor help

import java.text.*;
public class CarsV5
//default constructor
    CarsV5()
public int calcDistance(int sMiles, int eMiles)
    //calculate the distance
    return eMiles - sMiles;
public double calcMPG(int dist, double gals)
    //calculate the MPG
    return dist/gals;
public static void main(String[] args)
    //declaration of variables
    int startMiles1, endMiles1;
    int distAnce1;
    double gallons1;
    double mpg1;
    double mpg2;
    double gallons2;
    int startMiles2, endMiles2;
    int distAnce2;
    int startMiles3, endMiles3;
    int distAnce3;
    double gallons3;
    double mpg3;
    double pricePerGallon1 = 2.90;
    String carModel1 = "93 Toyota Camry";
    //decimal format
        DecimalFormat df = new DecimalFormat("0.00");
    //initialization of variables
    startMiles1 = 25000; endMiles1 = 25320; startMiles2 = 25320; endMiles2 = 25670; startMiles3 = 25670; endMiles3 = 26020;
    distAnce1 = 0; gallons1 = 16; distAnce2 = 0; gallons2 = 16; distAnce3 = 0; gallons3 = 17;
    mpg1 = 0; mpg2 = 0; mpg3 = 0;
       CarsV5 car1 = new CarsV5(carModel1, endMiles1, startMiles1, gallons1, pricePerGallon1);
    //call methods
    distAnce1 = car1.calcDistance(startMiles1, endMiles1);
    mpg1 = car1.calcMPG(distAnce1, gallons1);
    distAnce2 = car1.calcDistance(startMiles2, endMiles2);
    mpg2 = car1.calcMPG(distAnce2, gallons2);
    distAnce3 = car1.calcDistance(startMiles3, endMiles3);
    mpg3 = car1.calcMPG(distAnce3, gallons3);
    //print results
    System.out.println("Type of Car     Start Miles     End Miles    Distance   Gallons   Miles/Gal");
    System.out.println("============================================================================");
    System.out.println(carModel1 + "       " + startMiles1 + "         " + endMiles1 + "        " + distAnce1 + "       " + gallons1 + "       " + mpg1);
    System.out.println(carModel1 + "       " + startMiles2 + "         " + endMiles2 + "        " + distAnce2 + "       " + gallons2 + "       " + mpg2);
    System.out.println(carModel1 + "       " + startMiles3 + "         " + endMiles3 + "        " + distAnce3 + "       " + gallons3 + "       " + df.format(mpg3));When I try to compile, it tells me that "cannot find symbol ; constructor class CarsV5(contents)" I declared it right there, do I have it in the wrong place or something?
Edited by: singramsan89 on Feb 4, 2008 6:09 PM

public class ShapesV5
    //private instance variables
    int mySide1, mySide2;
    //default constructor
    ShapesV5()
    //constructor with two parameters
    ShapesV5 (int s1, int s2)
        mySide1 = s1;
        mySide2 = s2;
    //calculate area of a triangle
    public double calcTriArea()
        return mySide1 * mySide2 * .5;
    //calculate the hypoteneuse of a right triangle
    public double calcHypoteneuse()
        return Math.sqrt(Math.pow(mySide1, 2) + Math.pow(mySide2, 2));
    //main method
    public static void main(String[] args)
        //declaration of variables
        int side1, side2, radius;
        double triArea, circArea, hypoteneuse, circumference;
        //initialization of variables
        side1 = 10; side2 = 5;
        triArea = 0; hypoteneuse = 0;
        ShapesV5 shapes = new ShapesV5(side1, side2);
        //call methods
        triArea = shapes.calcTriArea();
        hypoteneuse = shapes.calcHypoteneuse();
        //print results
        System.out.printf(" Triangle Area = %8.2f%n", triArea);
        System.out.printf("   Hypoteneuse = %8.2f%n", hypoteneuse);
}is it this what I'm trying to do? I think so...this is a new code that worked fine. I guess it's just where I was working with an old code and trying to do it in a new manner...but I'm going to use this and model my next one off of it.
Thanks, I get it now.

Similar Messages

  • Default Constructor Help?

    class A {
    public A() {
    public A(int) {
    //--main method--
    }This is an assignment that I'm having some trouble with So let's say I have class A and the default constructor, as well as a constructor that takes an int. The default A constructor is supposed to have an object created by a call to the default constructor of objects, java.lang.Object. However, if I try to refer to the default Object() constructor by using super();, it creates a NullPointerException error (obviously). So is there some sort of default object or something that I'm supposed to use?
    Thanks for all the help :)

    I mean it generates the error during runtime; i can compile it okay.Sorry, I missed that you said it was a NullPointerException.
    For example, it seems to generate the error on the line A.getClass(); even though I don't think it should.That line isn't in the code you posted. The same thing applies really: post a brief example that gives the runtime error along with the exact stack trace that is produced.

  • Multiple constructor help needed

    Good day to all.
    I have an object that has 2 constructors. I want the first constructor to be able to call the second. Is this possible?
    Pseudo example.....
    public class O{
      int val;
      public O(String S) throws Exception{
        int i = Integer.parseInt(S);
        new O(i);
      public O(int v){
        this.val = v;
    }Thanks

    Something like:
    public class O{
      int val;
       public O(String S){
       try{
         this(Integer.parseInt(S));
       }catch(NumberFormatException e){
        System.out.println("Unconvertable String")
       public O(int v){
         this.val = v;

  • What the heck am I doing wrong???

    The error message I'm getting is the following: "week4_herbie must be defined in its own file" The problem that I'm running into is that the programs are supposed to work together. One (week4_herbie) handles the mortgage calculation itself (and set up the GUI) and send the information to the amoritizeFrame program, which is designed to display the amoritization table. The numericTextFrame is to make sure that the variable input is acceptable. Here is the coding:
    week4_herbie
    The Amortization Schedule was constructed with my own class called AmortFrame
    that extends JFrame and a JTextArea that was added to a JScrollPane.
    // Imports needed libraries
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    // Event handling:implements listener interface for receiving action events.
    public class week4_herbie implements ActionListener
         // GUI Components
         JFrame calculatorFrame;
         JPanel calculatorPanel;
         AmortizeFrame amortFrame;   //local class for amortization schedule
         //  user input fields
         //  Loan amount entered as user text input from keyboard
         //  Term (in years) selected from a combo box
         //  Rate (%) selected from a combo box
         numericTextField loan;
         JComboBox rate;
         JComboBox term;
         // set up arrays for the selectable term and rate
        int[] loanTerm = new int[3];
        String[] loanTermString = new String[3];
        double[] loanRate = new double[3];
        String[] loanRateString = new String[3];
        // static variables, belong to class on not an instance
         static String sWindowTitle = "Brian's Week 3 - Mortgage Calculator";
         static String scolHeader = "Payment#\tPayment\tInterest\tCumInterest\tPrincipal\tBalance\n";
         static String slineOut = "________\t_______\t________\t___________\t_________\t_______\n";
         static String sfinalInstructions1 = "\nYou can leave windows open and enter new value or close either window to exit\n";
         JLabel loanLabel,termLabel, rateLabel, pmtLabel;
         JButton calculate;
        public week4_herbie()
              // Before progressing, read in the data
              if(readData())
                   //Create and set up the window.
                   calculatorFrame = new JFrame(sWindowTitle);
                   calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // Set size of user input frame;
                   calculatorFrame.setBounds(0,0,100,100);
                   //Create and set up the panel with 4 rows and 4 columns.
                   calculatorPanel = new JPanel(new GridLayout(4, 4));
                   //Add the widgets.
                   addWidgets();
                   //Set the default button.
                   calculatorFrame.getRootPane().setDefaultButton(calculate);
                   //Add the panel to the window.
                   calculatorFrame.getContentPane().add(calculatorPanel, BorderLayout.
                   CENTER);
                   //Display the window.
                   calculatorFrame.pack();
                   calculatorFrame.setVisible(true);
              }// good data read
        }// end constructor
        private boolean readData()
              boolean isValid = true;
            loanRateString[0] = "5.35%";
            loanRateString[1] = "5.5%";
            loanRateString[2] = "5.75%";
            loanTermString[0] = "7 Years";
            loanTermString[1] = "15 Years";
            loanTermString[2] = "30 Years";
            loanRate[0] = 5.35;
            loanRate[1] = 5.5;
            loanRate[2] = 5.75;
            loanTerm[0] = 7;
            loanTerm[1] = 15;
            loanTerm[2] = 30;
            return isValid;
         }// end readData
        // Creates and adds the widgets to the user input frame.
        private void addWidgets()
            // numericTextField is a JTextField with some error checking for
            // non  numeric values.
            loan = new numericTextField();
            rate = new JComboBox(loanRateString);
              term = new JComboBox(loanTermString);
            loanLabel = new JLabel("Loan Amount", SwingConstants.LEFT);
            termLabel = new JLabel(" Term ", SwingConstants.LEFT);
            rateLabel = new JLabel("  Interest Rate ", SwingConstants.LEFT);
            calculate = new JButton("Calculate");
            pmtLabel  = new JLabel("Monthly Payment", SwingConstants.LEFT);
            //Listen to events from the Calculate button.
            calculate.addActionListener(this);
            //Add the widgets to the container.
            calculatorPanel.add(loan);
            calculatorPanel.add(loanLabel);
            calculatorPanel.add(term);
            calculatorPanel.add(termLabel);
            calculatorPanel.add(rate);
            calculatorPanel.add(rateLabel);
            calculatorPanel.add(calculate);
            calculatorPanel.add(pmtLabel);
            //set label border size
            loanLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            pmtLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        } // end addWidgets
        // Event handling method invoked when an action occurs.
        // Processes each of the fields and includes error checking
        // to make sure each field has data in it and then calculates
        // actual payment.
        public void actionPerformed(ActionEvent event)
            double tamount = 0; //provides floating point for total amount of the loan
            int term1      = 0; //provides int for the term
            double rate1   = 0; //provides floating point for the percentage rate.
            // get string to test that user entered
                String testit = loan.getText();          // get user entered loan amount
                // if string is present
                if(testit.length() != 0)
                   tamount = (double)(Double.parseDouble(testit)); // convert to double
                   // first value valid - check second one, term value
                   // get the index of the item the user selected
                   // then get the actual value of the selection from the
                   // loanTerm array
                   int boxIndex = term.getSelectedIndex();
                   if(boxIndex != -1)
                        term1 = loanTerm[boxIndex];
                        // second value valid - check third one, interest rate
                        // get the index of the item the user selected
                       // then get the actual value of the selection from the
                       // loanRate array
                       boxIndex = rate.getSelectedIndex();
                       // if something is selected in rate combo box
                        if(boxIndex != -1)
                            rate1 = loanRate[boxIndex];
                             // all three values were good so calculate the payment
                        double payment = ((tamount * (rate1/1200)) /
                                              (1 - Math.pow(1 + rate1/1200, -term1*12)));
                        // format string using a mask
                        java.text.DecimalFormat dec = new java.text.DecimalFormat(",###.00");
                        String pmt = dec.format(payment);
                        // change foreground color of font for this label
                        pmtLabel.setForeground(Color.green); //
                        // set formatted payment
                             pmtLabel.setText(pmt);
                             // generate the amortization schedule
                             amortize(tamount, rate1*.01, term1*12, payment);
                        else  //third value was bad
                             Toolkit.getDefaultToolkit().beep(); // invokes audible beep
                             pmtLabel.setForeground(Color.red);  // sets font color
                             pmtLabel.setText("Missing Field or bad value");  // Error Message
                        }// end validate third value
                   else  // second value was bad
                        Toolkit.getDefaultToolkit().beep();
                        pmtLabel.setForeground(Color.red);
                        pmtLabel.setText("Missing Field or bad value");
                   }// end validate second value
              else  // first value was bad
                   Toolkit.getDefaultToolkit().beep();
                   pmtLabel.setForeground(Color.red);
                 pmtLabel.setText("Missing Field or bad value");
              }// end validate first value
        }// end actionPerformed
         // calculate the loan balance and interest paid for each payment over the
         // term of the loan and list it in a separate window - one line per payment.
         public void amortize(double principal, double APR, int term,
                              double monthlyPayment)
              double monthlyInterestRate = APR / 12;
              //double totalPayment = monthlyPayment * term;
              int payment = 1;
              double balance = principal;
              int num = 0;
              double monthlyInterest;
              double cumInterest = 0;
            // if the frame for the amortization schedule has not been created
            // yet, create it.
              if(amortFrame == null)
                 amortFrame = new AmortizeFrame();
              // obtain a reference to our text area in our frame
              // and update this as we go through
              JTextArea amortText = amortFrame.getAmortText();
              // formatting mask
              java.text.DecimalFormat df= new java.text.DecimalFormat(",###.00");
              // set column header
              amortText.setText(scolHeader);
              amortText.append(slineOut);
              // loop through our amortization table and add to
              // JTextArea
              while(num < term)
                   monthlyInterest = monthlyInterestRate * balance;
                   cumInterest += monthlyInterest;
                   principal = monthlyPayment - monthlyInterest;
                   balance -= principal;
                   //Show Amortization Schedule
                   amortText.append(String.valueOf(payment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyPayment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(cumInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(principal));
                   amortText.append("\t ");
                   amortText.append(df.format(balance));
                   amortText.append("\n");
                   payment++;
                   num++;
              // print the headers one more time at the bottom
              amortText.append(slineOut);
              amortText.append(scolHeader);
              amortText.append(sfinalInstructions1);
         }// end amortize
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
             //Note this next line only works with JDK 1.4 and higher
            JFrame.setDefaultLookAndFeelDecorated(true);
            week4_herbie calculator = new week4_herbie();
        // main method
        public static void main(String[] args)
             // allow user to set a different file from
             // command line
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }// end classAmoritizeFrame
    import java.awt.*;
    import javax.swing.*;
    // this class provides the frame and the scrolling text area for the
    // amortization schedule
    class AmortizeFrame extends JFrame
         private JTextArea amortText;
         private JScrollPane amortScroll;
         private String sTitle = "Brian's";
         final String sTitle2 = " Amortization Schedule";
         // default constructor
         public AmortizeFrame()
              initWindow();
         // constructor that takes parameter (such as week number)
         // to add extra info to title on frame of window
         public AmortizeFrame(String week)
              sTitle = sTitle + " " + week;
              initWindow();
         }// end constructor
         // helper method that initialized GUI
         private void initWindow()
              setTitle(sTitle + sTitle2);
              setBounds(200,200,550,400);
              Container contentPane=getContentPane();
              amortText = new JTextArea(7,100);
              amortScroll= new JScrollPane(amortText);
              contentPane.add(amortScroll,BorderLayout.CENTER);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         // method to get the text area for users of
         // this frame.  They can then add whatever text they want from the outside
         public JTextArea getAmortText()
              return amortText;
    }// end amortizeFramenumericTextFrame
    * This is a control that subclasses the
    * JTextField class and through a keyboard
    * listener only allows numeric input, decimal point
    * and backspace into the text field.
    * Known Problems!!!:
    * 1) It will not catch if the user
    *    enters two decimal points
    import java.awt.Toolkit;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JTextField;
       A JTextField subclass component that
       only allowing numeric input.  
    class numericTextField extends JTextField
        private void setUpListener()
            addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e)
                            char c = e.getKeyChar();
                    if(!Character.isDigit(c) && c != '.' && c != '\b' && c != '\n' && c != '\177')
                        Toolkit.getDefaultToolkit().beep();
                        e.consume();
        numericTextField(int i)
             super(i);
               setUpListener();
        public numericTextField()
              setUpListener();
    }Thanks for the assist

    Top-level classes (that is, classes not inside other classes) must be defined as public or package-private (the default access level if you do not provide one).
    A public top-level class Foo must be contained in Foo.java.
    A non-public top-level class Foo can be contained in any .java file.

  • 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 on parameterized constructor please

    So i have a menuing system. I create each window in a new class, but the problem is to detect which button is pressed in one of the provider classes by the driver class. I want the driver class to detect i have pressed for instance "list" to run the list class. Here i thought parameterized constructors would work best to get the variables across, but for some reason it is not working. Here is the code: (The gui works and detects the button is pushed etc.)
    Provider class:
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    public class MainMenu implements ActionListener
         public String choice = "";
         public MainMenu(String c)
              choice = c;
         JFrame jf = new JFrame("Main Menu");
         Toolkit tk = Toolkit.getDefaultToolkit ();
        int x = (int) tk.getScreenSize ().getWidth ();
        int y = (int) tk.getScreenSize ().getHeight ();
        ImageIcon ev = new ImageIcon("event.png");
        ImageIcon lb = new ImageIcon("list.png");
        ImageIcon cv = new ImageIcon("vote.png");
        ImageIcon bb = new ImageIcon("bio.png");
        Font f1 = new Font ("Tahoma", Font.BOLD, 25);
        Font f2 = new Font ("Chiller", Font.BOLD, 100);
        JLabel lbl = new JLabel("MAIN MENU");
        JLabel space = new JLabel ("");
         JButton jb1 = new JButton("Events", ev);
         JButton jb2 = new JButton("Leader Board", lb);
         JButton jb3 = new JButton("Cast Vote", cv);
         JButton jb4 = new JButton("Band Biographies", bb);
         GridLayout grid = new GridLayout(10,10,1,1);
         JPanel jp0 = new JPanel();
         JPanel jp1 = new JPanel();
         JPanel jp2 = new JPanel();
         JPanel jp3 = new JPanel();
         JPanel jp4 = new JPanel();
         public MainMenu()
             lbl.setFont(f2);
             jf.setBounds(0,0, x,y);
              jf.setVisible(true);
              jf.setResizable(false);
              jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              jb1.addActionListener(this);
              jb2.addActionListener(this);
              jb3.addActionListener(this);
              jb4.addActionListener(this);
              jb1.setFont(f1);
              jb2.setFont(f1);
              jb3.setFont(f1);
              jb4.setFont(f1);
              jp0.add(lbl);
             jp1.add(jb1);
             jp2.add(jb2);
             jp3.add(jb3);
             jp4.add(jb4);
             jf.setLayout(grid);
             jf.add(space);
             jf.add(space);
             jf.add(jp0);
             jf.add(space);
             jf.add(jp1);
             jf.add(jp2);
             jf.add(jp3);
             jf.add(jp4);
             jf.repaint();
        public void actionPerformed (ActionEvent e)
             if (e.getSource () == jb1)
                  choice = "events";
                  System.out.println(choice);//Just to test whether the buttons work...
             else if (e.getSource () == jb2)
                  choice = "list";
                  System.out.println(choice);
             else if (e.getSource () == jb3)
                  choice = "vote";
                  System.out.println(choice);
             else if (e.getSource () == jb4)
                  choice = "bio";
                  System.out.println(choice);
        public String getChoice()
             return choice;
    }and here is the driver class which doesnt read the change in the choice variable:
    public class PAT
        public static void main(String[] args) //implements ActionListener
              String choice = "";
              MainMenu mm = new MainMenu(choice);
              new MainMenu();
              while (choice.equals(""))
              if (choice.equals("list"))
                   System.out.println("Parameterized constructor works");
    }Any help or advice would be greatly appreciated. Thanks in advance.

    Here is exactly what im trying to do. Im making a menu system. It consists of several windows. For instance main menu has 3 buttons. each button takes you to a new window. Each new window has a back button to return to the main menu. and then the new windows might also have buttons to go to another new window and will have buttons too.
    Im making each window (menu window) in a new class. I want to be able to call these classes (windows) as desired. so all the loops and so on to run the different windows at the right times should be in the main class. makes it easier, as ill be jumping around between programs much less. i just want my parameterized constructors to work, because i believe this will be the easiest way. to have variables, that if changed in one of the provider classes, they will change in the driver class too. this way all i do is change a variable when a button i clicked in the provider classes. then the driver class does a certain action according to the value of the variable read from the provider classes. for instance my choice variable (which is now an int) detects what button is clicked. then my driver class runs the next window based on the value of choice which it recieved from the other classes.
    I hope it makes sense.
    Thank you for the quick replies.

  • 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.

  • Need some help with a task, constructors.

    Hi there, I've got this task here, and I was wondering if someone could help me out. I wan't to know if my code is answering my task.
    The task:
    BlueJ casino in Las Vegas has given you this task to create a class where they can register their players. You should create a new project and a class called Player. The purpose with this task is that player information could be captured to a secure object and that it couldn't be changed arbitrary.
    The class Player should therefore contain the private fields 'firstname', 'lastname' and 'credits'.
    The official methods that player should define, does the following:
    - setFirstname: Sets the first name to the player
    - getFirstname: Returns the first name to the player
    - setLastname: Sets the last name to the player
    - getLastname: Returns the last name to the player
    - addCredits: Adds the player's credits to a given amount
    - getCredits: Returns the player's credits.
    - validPlayer: Checks if the player credits is higher greater zero, with an if sentence. If it is greater, it should return 'true', otherwise, it should return 'false'.
    - print: Prints the player information to the terminal window (with System.out.println).
    The class Player should also have a constructor that gets two arguments/current parameters to initialize the Player object:
    - A text string that represents the player's first name.
    - A text string that represents the player's last name.
    - The constructor should also set the player's credits to 100.
    My code so far:
    public class Player {
        private String firstname;
        private String lastname;
        private int credits;
        public Player(String firstname, String lastname, int credits) {
           this.firstname = "";
           this.lastname = "";
           this.credits = 100;
        public void setFirstname(String name) {
            firstname = name;
        public String getFirstname() {
            return firstname;
        public void setLastname(String name) {
            lastname = name;
        public String getLastname() {
            return lastname;
        public void addCredits(int amount) {
            credits = credits + amount;
        public int getCredits() {
            return credits;
        public boolean validPlayer() {
            if(getCredits() > 0){
                return true;
            } else {
                return false;
        public void print() {
            System.out.println("PLAYER INFORMATION:");
            System.out.println("First name: " + getFirstname());
            System.out.println("Last name: " + getLastname());
            System.out.println("Credit: " + getCredits());
            System.out.println("-------------------");
    }Please give me some help here, and please show me some code! Thanks for any help!

    Thanks again.
    What about this?public class Player {
        private String firstname;
        private String lastname;
        private int credits;
        public Player(String firstname, String lastname) {
           this.firstname = firstname;
           this.lastname = lastname;
           this.credits = 100;
        public void setFirstname(String name) {
            firstname = name;
        public String getFirstname() {
            return firstname;
        public void setLastname(String name) {
            lastname = name;
        public String getLastname() {
            return lastname;
        public void addCredits(int amount) {
            credits = credits + amount;
        public int getCredits() {
            return credits;
        public boolean validPlayer() {
            if(getCredits() > 0){
                return true;
            } else {
                return false;
        public void print() {
            System.out.println("PLAYER INFORMATION:");
            System.out.println("First name: " + getFirstname());
            System.out.println("Last name: " + getLastname());
            System.out.println("Credit: " + getCredits());
            System.out.println("-------------------");
    }Edit: Oh, yeah - could I write the addCredits() like this?    public void addCredits(int amount) {
            amount+=credits;
        }Edited by: JKM123 on Feb 1, 2009 3:22 PM
    Edited by: JKM123 on Feb 1, 2009 3:24 PM

  • 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

  • Help with constuctor, need to rewrite program with this constructor

    i need to use this constructor for my Scholar class:
    public Scholar(String fullName, double gradePointAverage, int essayScore, boolean scienceMajor){here is the project that i'm doing:
    http://www.cs.utsa.edu/~javalab/cs17.../project1.html
    here's my code for the Scholar class:package project1;
    import java.util.*;
    public class Scholar implements Comparable {
        private static Random rand;
        private String fullName;
        private double gradePointAverage;
        private int essayScore;
        private int creditHours;
        private boolean scienceMajor;
        private String lastName;
        private String firstName;
        private double totalScore;
        /** Creates a new instance of Scholar */
            public Scholar(String lastName, String firstName){
                    this.fullName = lastName + ", " + firstName;
                    this.gradePointAverage = gradePointAverage;
                    this.essayScore = essayScore;
                    this.creditHours = creditHours;
                    this.scienceMajor = scienceMajor;
                    this.rand = new Random();
            public String getFullName(){
                return fullName;
            public double getGradePointAverage(){
                return gradePointAverage;
            public int getEssayScore(){
                return essayScore;
            public int getCreditHours(){
                return creditHours;
            public boolean getScienceMajor(){
                return scienceMajor;
            public String setFullName(String lastName, String firstName){
               fullName = lastName + ", " + firstName;
               return fullName;
            public double setGradePointAverage(double a){
                gradePointAverage = a;
                return gradePointAverage;
            public int setEssayScore(int a){
                essayScore = a;
                return essayScore;
            public int setCreditHours(int a){
                creditHours = a;
                return creditHours;
            public boolean setScienceMajor(boolean a){
                scienceMajor = a;
                return scienceMajor;
            public void scholarship(){
                Random doubleGrade = new Random ();
                Random intGrade = new Random ();
                gradePointAverage = doubleGrade.nextDouble() + intGrade.nextInt(4);
                Random score = new Random();
                essayScore = score.nextInt(6);
                Random hours = new Random();
                creditHours = hours.nextInt(137);
                Random major = new Random();
                int num1 = major.nextInt(3);
                if (num1 == 0)
                    scienceMajor = true;
                else
                    scienceMajor = false;
            public double getScore(){
                totalScore = (gradePointAverage*5) + essayScore;
                if (scienceMajor == true)
                    totalScore += .5;
                if (creditHours >= 60 && creditHours <90)
                    totalScore += .5;
                else if (creditHours >= 90)
                    totalScore += .75;
                return totalScore;
            public int compareTo(Object obj){
                Scholar otherObj = (Scholar)obj;
                double result = getScore() - otherObj.getScore();
                if (result > 0)
                    return 1;
                else if (result < 0)
                    return -1;
                return 0;
            public static Scholar max(Scholar s1, Scholar s2){
                if (s1.getScore() > s2.getScore())
                    System.out.println(s1.getFullName() + " scored higher than " +
                            s2.getFullName() + ".\n");
                else
                    System.out.println(s2.getFullName() + " scored higher than " +
                            s1.getFullName() + ".\n");
                return null;
            public static Scholar max(Scholar s1, Scholar s2, Scholar s3){
                if (s1.getScore() > s2.getScore() && s1.getScore() > s3.getScore())
                    System.out.println(s1.getFullName() + " scored the highest" +
                            " out of all three students.");
                else if (s2.getScore() > s1.getScore() && s2.getScore() > s3.getScore())
                    System.out.println(s2.getFullName() + " scored the highest" +
                            " out of all three students.");
                else if (s3.getScore() > s2.getScore() && s3.getScore() > s1.getScore())
                    System.out.println(s3.getFullName() + " scored the highest" +
                            " out of all three students.");
                return null;
            public String toString(){
                return  "Student name: " + fullName + " -" + " Grade Point Average: "
                        + gradePointAverage  + ". " + "Essay Score: " + essayScore + "."
                        + " Credit Hours: " + creditHours + ". "  +  " Science major: "
                        + scienceMajor + ".";
    }here's my code for the ScholarTester class:package project1;
    import java.util.*;
    public class ScholarTester {
    public static void main(String [] args){
    System.out.println("This program was written by Kevin Brown. \n");
    System.out.println("--------Part 1--------\n");
    Scholar abraham = new Scholar("Lincoln", "Abraham");
    abraham.scholarship();
    System.out.println(abraham);
    /*kevin.setEssayScore(5);
    kevin.setGradePointAverage(4.0);
    kevin.setCreditHours(100);
    kevin.setFullName("Brown", "Kevin J");
    kevin.setScienceMajor(true);
    System.out.println(kevin);*/
    Scholar george = new Scholar("Bush", "George");
    george.scholarship();
    System.out.println(george + "\n");
    System.out.println("--------Part 2--------\n");
    System.out.println(abraham.getFullName() + abraham.getScore() + ".");
    System.out.println(george.getFullName() + george.getScore() + ".\n");
    System.out.println("--------Part 3--------\n");
    if(abraham.compareTo(george) == 1)
        System.out.println(abraham.getFullName() + " scored higher than " +
                abraham.getFullName() + ".\n");
    else
        System.out.println(abraham.getFullName() + " scored higher than " +
                abraham.getFullName() + ".\n");
    System.out.println("--------Part 4--------\n");
        Scholar.max(abraham, george);
        Scholar thomas = new Scholar("Jefferson", "Thomas");
        thomas.scholarship();
            System.out.println("New student added - " + thomas + "\n");
            System.out.println(abraham.getFullName() + " scored " +
                    abraham.getScore() + ".");
            System.out.println(george.getFullName() + " scored " +
                    george.getScore() + ".");
            System.out.println(thomas.getFullName() + " scored " +
                    thomas.getScore() + ".\n");
        Scholar.max(abraham, george, thomas);
    }everything runs like it should and the program is doing fine, i just need to change the format of the Scholar constructor and probably other things. Can someone please give me an idea how to fix this.
    Thanks for taking your time reading this.

    then don't reply if you're not going to read it, i
    just gave the url, Don't get snitty. I'm just informing you that most people here don't want to click a link and read your whole bloody assignment. If you want help, the burden is on you to make it as easy as possible for people to help you. I was only trying to inform you about what's more likely to get you help. If doing things your way is more important to you than increasing your chances of being helped, that's your prerogative.
    so you can get an idea on what
    it's about, and yeah i know how to add a constructor,
    that's very obvious, That's what I thought, but you seemed to be saying, "How do I add this c'tor?" That's why I was asking for clarification about what specific trouble you're having.
    i just want to know how to
    implement everything correctly, so don't start
    flaming people. I wasn't flaming you in the least. I was informing you of how to improve your chances of getting helped, and asking for clarification about what you're having trouble with.

  • Help on using NewObject with constructors!

    Hi,All:
    I want to create an object in a native method. The object is an instance of an inner class. The inner class has two constructors: one default and one with two arguments. There is no problem if I use NewObject with the default construtor. But if I use NewObject with the constructor taking two int arguments. The JVM crashes.
    Can anybody give me some idea what the problem is?
    Thanks!
    Tao
    Here is the native method, the inner class and error message:
    JNIEXPORT jobject JNICALL Java_Prompt_createtp(JNIEnv *env, jobject obj)
         jobject test_ttt= 0;
         jclass cls2;
         jmethodID cid;     
         jint a,b;
         jfieldID fid;
         a = 10; b = 20;
         cls2 = (*env)->FindClass(env,"LPrompt$tp;");          
         cid = (*env)->GetMethodID(env,cls2,"<init>","(LPrompt;II)V");     
    test_ttt = (*env)->NewObject(env,cls2,cid,a,b);
    // However, the following codes using default constructor works well
    //cid = (*env)->GetMethodID(env,cls2,"<init>","(LPrompt;)V");     
    //test_ttt = (*env)->NewObject(env,cls2,cid);
    (*env)->DeleteLocalRef(env,cls2);
         return test_ttt;
    // here is the inner class     
    class tp{
    int a;
    int b;
    tp(){
    a = 100;
    b = 0;
    tp(int x,int y){
    a = x; b = y;
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # Internal Error (53484152454432554E54494D450E43505001A3), pid=276, tid=640
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
    # An error report file with more information is saved as hs_err_pid276.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    #

    You are getting the constructor id on a signature that looks like:
    Prompt(Prompt p, int n1, int n2)I guess that your constructor signature is:
    Prompt(int n1, int n2)So it should ne:
    cid = (*env)->GetMethodID(env,cls2,"<init>","(II)V");Next time please paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    You may read the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips for more information.
    Regards

  • Help with first approach to Class and Constructor

    Hello guys
    I have a homework but I'm totally lost.
    Here is the assignment:
    **Write the fields, the constructor and the methods of the class below.**
    **public class HourlyEmployee**
    **The class has 4 private fields:**
    **private String name; // the name**
    **private String position; // the position in the company**
    **private double rate; // the hourly rate**
    **private double hours = 0.0; // the hours that the employee worked**
    **The constructor has the header**
    **public HourlyEmployee( String n, Spring pos, double pay)**
    **that puts n into name, pos into position, and pay into rate.**
    **The class has the methods below.**
    **public String getName()**
    **public String getPosition()**
    **public double getRate()**
    **public double getHours()**
    **public void setName(String newName)**
    **public void getARaise(double inc)**
    **public void work(double time)**
    **public double getPaid()**
    **public boolean equals(HourlyEmployee other)**
    **public String toString()**
    **The first 4 methods return the name, the position, the rate**
    **and the hours, in this order.**
    **The method getARaise adds inc to rate.**
    **The method work adds time to hours.**
    **The program getPaid computes and returns the weekly pay.**
    **The worker gets paid one time and a half for overtime (over**
    **40 hours of work). Don't forget to reset hours to 0 before**
    **you leave this method.**
    **The method**
    **public boolean equals(HourlyEmployee other)**
    **returns true if this is equals to other and false**
    **if they are not. Two hourly employees are equal**
    **if they have the same name, the same position and**
    **the same rate.**
    **The last method returns the string**
    **HourlyEmployee[name = ...][position = ....][rate = ...]**
    **where ... stands for the name, position, and the rate**
    **of the employee.**
    Here is what I have so far:
    public class HourlyEmployee
    *// the fields*
    private String name; // the name
    private String position; // the position in the company
    private double rate; // the hourly rate
    private double hours = 0.0; // the hours that the employee worked
    *// This constructor sets the name, position and rate*
    */ @param n is the name*
    *@param pos is the position*
    *@param pay is the rate*
    public HourlyEmployee( String n, String pos, double pay)
    name = n;
    position = pos;
    rate = pay;
    *//get a new name*
    *//@param newName is the new name to be entered*
    public void setName (String newName)
    <
    +//get a raise+
    +//@param inc is the amount to be increased+
    public void getARaise (double inc)*
    *+{+*
    rate = inc;*
    System.out.println ("The rate is " rate);*
    +}+
    +//get the time worked+
    +//@param time is the amount of hours worked+
    public void work (double time)*
    *+{+*
    hours = time;*
    System.out.println ("The amount of hour is " hours);*
    +}+
    +//get the amount paid+
    +//@param rate is the amount of money+
    public void getPaid ()*
    *+{+*
    rate = hours;*
    if ( hours > 40 )*
    rate = 1.5; *
    System.out.println ("The amount paid is " rate);*
    *//compare employees*
    *//@param rate*
    public boolean equals (HourlyEmployee other)
    return rate == other.rate
    *&& name.equals (other.name);*
    But I don't really understand what's going on.
    What is the difference between setName and getName?
    Didn't the constructor set the name, the position and the rate already?
    I don't know where I'm standing or where I'm going.
    Any help?
    Thank you

    Ok, this is what I have so far:
    public class HourlyEmployee
             // the fields
            private String name; // the name
            private String position; // the position in the company
            private double rate; // the hourly rate
            private double hours = 0.0; // the hours that the employee worked
            // This constructor sets the name, position and rate
            /* @param n is the name
             * @param pos is the position
             * @param pay is the rate
            public HourlyEmployee( String n, String pos, double pay)
              name = n;
              position = pos;
                    rate = pay;
            //@param returns the name
            public String getName()
            return name;
            //@param returns the employee position
            public String getPosition()
            return position;
            //@param returns the hourly rate
            public double getRate()
            return rate;
            //@param returns the hours
            public double getHours()
            return hours;
            //get a new name
            //@param newName is the new name to be entered
            public void setName (String newName)
                    name = newName;
            //get a raise
            //@param inc is the amount to be increased
            public void getARaise (double inc)
                    rate += inc;
            //get the time worked
            //@param time is the amount of hours worked
            public void work (double time)
                    hours += time;
            //get the amount paid
            //@param rate is the amount of money
            public double getPaid ()
                   if ( hours > 40 )
                       double payment = rate*hours*40 + 1.5*rate*(hours-40);
                       double payment = rate * hours;
                    hours = 0.0;
            //compare employees
            //check if name, position and rate are the same
            public boolean equals (HourlyEmployee other)
            return name.equals (other.name)
                && position.equals (other.position)
                && rate == other.rate;
            //This method returns a string
            // with the name, position and rate of the employee
            public String toString()
                String myString = "HourlyEmployee[name =" + name
                        + "][position = " + position + "][rate= "
                        + rate + "]";
    }Now I have 2 problems:
    - The method getPaid is specified to return a double and gives me the error "missing return statement". How can I make it return a double?
    - The public String toString gives me the same error, I don't know why
    Any help?

  • Pls help..Constructor,setter, getter and Exception Handling Problem

    halo, im new in java who learning basic thing and java.awt basic...i face some problem about constructor, setter, and getter.
    1. I created a constructor, setter and getter in a file, and create another test file which would like to get the value from the constructor file.
    The problem is: when i compile the test file, it come out error msg:cannot find symbol.As i know that is because i miss declare something but i dont know what i miss.I post my code here and help me to solve this problem...thanks
    my constructor file...i dont know whether is correct, pls tell me if i miss something...
    public class Employee{
         private int empNum;
         private String empName;
         private double empSalary;
         Employee(){
              empNum=0;
              empName="";
              empSalary=0;
         public int getEmpNum(){
              return empNum;
         public String getName(){
              return empName;
         public double getSalary(){
              return empSalary;
         public void setEmpNum(int e){
              empNum = e;
         public void setName(String n){
              empName = n;
         public void setSalary(double sal){
              empSalary = sal;
    my test file....
    public class TestEmployeeClass{
         public static void main(String args[]){
              Employee e = new Employee();
                   e.setEmpNum(100);
                   e.setName("abc");
                   e.setSalary(1000.00);
                   System.out.println(e.getEmpNum());
                   System.out.println(e.getName());
                   System.out.println(e.getSalary());
    }**the program is work if i combine this 2 files coding inside one file(something like the last part of my coding of problem 2)...but i would like to separate them....*
    2. Another problem is i am writing one simple program which is using java.awt interface....i would like to add a validation for user input (something like show error msg when user input character and negative number) inside public void actionPerformed(ActionEvent e) ...but i dont have any idea to solve this problem.here is my code and pls help me for some suggestion or coding about exception. thank a lots...
    import java.awt.*;
    import java.awt.event.*;
    public class SnailTravel extends Frame implements ActionListener, WindowListener{
       private Frame frame;
       private Label lblDistance, lblSpeed, lblSpeed2, lblTime, lblTime2, lblComment, lblComment2 ;
       private TextField tfDistance;
       private Button btnCalculate, btnClear;
       public void viewInterface(){
          frame = new Frame("Snail Travel");
          lblDistance = new Label("Distance");
          lblSpeed = new Label("Speed");
          lblSpeed2 = new Label("0.0099km/h");
          lblTime = new Label("Time");
          lblTime2 = new Label("");
          lblComment = new Label("Comment");
          lblComment2 = new Label("");
          tfDistance = new TextField(20);
          btnCalculate = new Button("Calculate");
          btnClear = new Button("Clear");
          frame.setLayout(new GridLayout(5,2));
          frame.add(lblDistance);
          frame.add(tfDistance);
          frame.add(lblSpeed);
          frame.add(lblSpeed2);
          frame.add(lblTime);
          frame.add(lblTime2);
          frame.add(lblComment);
          frame.add(lblComment2);
          frame.add(btnCalculate);
          frame.add(btnClear);
          btnCalculate.addActionListener(this);
          btnClear.addActionListener(this);
          frame.addWindowListener(this);
          frame.setSize(100,100);
          frame.setVisible(true);
          frame.pack();     
        public static void main(String [] args) {
            SnailTravel st = new SnailTravel();
            st.viewInterface();
        public void actionPerformed(ActionEvent e) {
           if (e.getSource() == btnCalculate){
              SnailData sd = new SnailData();
           double distance = Double.parseDouble(tfDistance.getText());
           sd.setDistance(distance);
                  sd.setSpeed(0.0099);
              sd.setTime(distance/sd.getSpeed());
              String answer = Double.toString(sd.getTime());
              lblTime2.setText(answer);
              lblComment2.setText("But No Exception!!!");
           else
           if(e.getSource() == btnClear){
              tfDistance.setText("");
              lblTime2.setText("");
       public void windowClosing(WindowEvent e){
                   System.exit(1);
        public void windowClosed (WindowEvent e) { };
        public void windowDeiconified (WindowEvent e) { };
        public void windowIconified (WindowEvent e) { };
        public void windowActivated (WindowEvent e) { };
        public void windowDeactivated (WindowEvent e) { };
        public void windowOpened(WindowEvent e) { };
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;
    }Pls and thanks again for helps....

    What i actually want to do is SnailTravel, but i facing some problems, which is the
    - Constructor,setter, getter, and
    - Exception Handling.
    So i create another simple contructor files which name Employee and TestEmployeeClass, to try find out the problem but i failed, it come out error msg "cannot find symbol".
    What i want to say that is if i cut below code (SnailTravel) to its own file(SnailData), SnailTravel come out error msg "cannot find symbol".So i force to put them in a same file(SnailTravel) to run properly.
    I need help to separate them. (I think i miss some syntax but i dont know what)
    And can somebody help me about Exception handling too pls.
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;

  • 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

Maybe you are looking for

  • Vendor Master Record & MRP

    Hi All , If i want to pull out a specific field from Vendor master so that it gets populated in PR(which is made after MRP run ) , is it possible? I am actually trying to input a particular no. in the vendor master and then pull it through PR. So I w

  • Searching folder of pdfs by keywords only, not text in body

    in pro 9: I have a large collection of pdfs in folders. I want to be able to search for a subset of pdfs using only the keywords which I entered in the metadata field. I don't want pdfs which have those words in the body of the pdfs, just in the meta

  • Convert REM Files to MP3 Format?

    I have downloaded several songs via the Amazon MP3 application on my Blackberry Curve 9300.  Little did I know that the songs were downloaded as rem files and not mp3 format?  I cannot upload the files to my desktop or laptop computers nor my Kindle.

  • Integracion servidor simbra con outlook CRM

    Buenas tardes, Tenemos un proyecto que va a pas pasar a el correo Zimbra de VMware, Necesitamos saber si el SERVIDOR  SIMBRA integrado con el Outlook CLIENTE funciona con el CRM de SAP BO? Quedo atenta a su respuesta, Saludos, YULI MARTINEZ

  • MobileMe syncing disabled on my iMac

    I have an iMac running OS10.5.8, an iPhone 3GS running OS4.0.2. I also have Outlook at work on a PC. Using MobileMe, I used to be able to sync my calendars & contacts between Outlook, my iPhone and iCal. Although the calendars sync between Outlook an