Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Only uses Default Constructor

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Only uses Default Constructor

    My class is currently working on Looping; Characters, Strings, and the StringBuffer Assignment and I'm having a bit of an issue with my code as it will only use the default constructor. On top of that instead of posting results in one message dialog box it posts it to multiple.

    The following is the assignment as it is written:
    Create a class named Investment. This class should have private variables for the amount invested and the years invested. The class should have a public symbolic constant for the interest rate. Use 12% (.12) for this constant. Create the following public methods in the Investment class.
    A default constructor.  This constructor will set the investment amount to 1000 and the years to one. Make each of these default values a symbolic constant. The constants should be public.
    An overloaded constructor that takes an argument for the amount and years. Edit each value to insure it is greater than zero. Use the default value if an argument value is zero or less. For example, use 1000 for the amount if the amount argument is zero.
    A get and set method for each private variable. Edit each value in its respective set method to insure it is greater than zero. Use the default value if an argument value is zero or less. For example, use 1000 for amount if the amount argument is zero.
    A method to calculate the annual return on the investment. You may calculate the annual balance in two ways. The first requires you to repeatedly multiply the amount invested by 1.12 (one plus the interest rate). Assume for example the investment amount is 2000 and the number of years is two. The calculation for the annual balance would be: 
    1st year amount = (1.12) * 2000 
    2nd year amount = (1.12) * 1st year amount
    The second method requires the use of the Math.pow method. Use the Math.pow method to raise a number to a power. This method returns a double and has two arguments - both doubles. The first number is the amount to be "raised" which is 1.12 (one plus the interest rate). The second number is the power to which it should be raised which is the number of years invested. Using the same amount and years as above, the calculation for the annual balance when investing $2000 for 2 years would be:
     
    year 1 amount = Math.pow(1.12, 1) * 2000
    year 2 amount = Math.pow(1.12, 2) * 2000
     
    You must use a loop to calculate the yearly amounts. You can't use multiple selection statements grouped together to attempt to cover all possible combinations of years and and amounts.
    This method must return a String that includes the output for each year. For example, the String created using the same amount and years as above would contain the following.
    The amount at end of year 1 is $2240 <new line character> The amount at end of year 2 is $2508
     
    Create a class named MakeInvestment. This class must create and use an object of the Investment class.
    Create a separate method in the MakeInvestment class to get the amount invested from the user. You must use an input dialog box like the one in Figure 1 below to get the input.
     
     
     
    The amount invested must be a number and must be greater than zero. To check for a number, inspect each character entered in the dialog to make sure it is a digit. Do not use exception processing or regular expressions to determine if the string is a valid number. (We will do this in a later assignment!) By checking for digits only, you will not allow a decimal point or a negative sign. Display an error dialog box if the data entered is not a number (Figure 2).
     
     
     
    After displaying either message dialog box, display the input dialog again to get a valid investment amount. Continue to display the input dialog and the appropriate error dialog until an acceptable value is entered.
     
    Create a separate method in the MakeInvestment class to get the number of years to invest from the user. You must use an input dialog box like the one in Figure 3 below to get the input.
     
     
     
    The number of years to invest must be a number and must be greater than zero. To check for a number, inspect each character entered in the dialog to make sure it is a digit. Do not use exception processing or regular expressions to determine if the string is a valid number. (We will do this in a later assignment!) By checking for digits only, you will not allow a decimal point or a negative sign. Display an error dialog box if the data entered is not a number (Figure 4).
     
     
    After displaying either message dialog box display the input dialog to get a valid number of years again.  Continue to display the input dialog and the appropriate error dialog until an acceptable value is entered.
     
    Display the output indicating the balance at the end of each investment year. Use a message dialog to display this output.  Using the same amount, years, and rate as above, the output when investing $2000 for 2 years at 12 % would be as displayed in Figure 5 below.
     
     
    The output when investing $5000 for 5 years at 12 % would be as displayed in Figure 6 below.
     
     
    Remember, the output displayed should be the String returned from the method in the Investment class that calculates the annual balances.
     
    You do not need to program a response when the user clicks the Cancel button or clicks the X in the upper right corner of the dialog in Figures 1 and 4. I will not test these features when I grade your application.
    The MakeInvestment class cannot have any "class wide" variables. This means all the variables in the MakeInvestment class must be defined within a method.


    So my current code for the Investment class is:

    import javax.swing.JOptionPane;
     
    public class Investment
     
    {
        private double moneyInvested;
        private double yearsInvested;
     
        public final static double AMOUNT_DEFAULT = 1000;
        public final static double YEARS_DEFAULT = 5;
     
        public final static double RATE = 0.12;
     
        public Investment()
        {
            moneyInvested = AMOUNT_DEFAULT;
            yearsInvested = YEARS_DEFAULT;
        }
     
        public Investment(double AMOUNT_DEFAULT, double YEARS_DEFAULT)
        {
            if (moneyInvested <= 0)
            {
                moneyInvested = AMOUNT_DEFAULT;
            }
     
            if (yearsInvested <= 0)
            {
                yearsInvested = YEARS_DEFAULT;
            }
        }
     
        public double getMoneyInvested(){return moneyInvested;}
        public double getYearsInvested(){return yearsInvested;}
     
        public void setMoneyInvested(double inputMoney)
        {
            moneyInvested = inputMoney;
     
            if (inputMoney <= 0)
            {
                inputMoney = 1000;
            }
        }
     
        public void setYearsInvested(double inputYears)
        {
            yearsInvested = inputYears;
     
            if (inputYears <= 0)
            {
                inputYears = 1;
            }
        }
     
        public static String returnValue(double inputYears, double inputMoney)
        {
            double returnInvestment;
            int initYears = 1;   
    	     String returnValue = "";
     
     
            while(initYears <= inputYears)
            {
                returnInvestment = Math.pow(1.12, initYears) * inputMoney;
                int investReturn = (int)returnInvestment;
     
                returnValue = "The amount at end of year " + initYears + " is " + investReturn;
     
                JOptionPane.showMessageDialog(null,returnValue);
                initYears++;
            }  
            return returnValue;
        }
    }

    and my code for the MakeInvestment class is:

    import javax.swing.JOptionPane; 
     
    public class MakeInvestment
    {
        public static void main(String[] args)
        {     
            Investment otherClass = new Investment(); 
            double yA = otherClass.YEARS_DEFAULT;
            double mA = otherClass.AMOUNT_DEFAULT;
     
            while (inputAmount() == false)
            {
                inputAmount();
            }
     
            while (inputYears() == false)
            {
                inputYears();
            }
     
            otherClass.returnValue(yA, mA);
     
        }
     
        public static boolean inputAmount()
        {
            String amountAmount = "";
     
            amountAmount = JOptionPane.showInputDialog(
                null, 
                "Enter the amount to invest (9999)." , 
                "Investment Amount" , JOptionPane.QUESTION_MESSAGE);
     
            if (amountAmount == null || amountAmount.length() == 0)
                {
                    JOptionPane.showMessageDialog(null, 
                    "Nothing entered - You must enter a number for amount invested.", 
                    "Investment Amount Error", JOptionPane.ERROR_MESSAGE);
                    return false;
                }
     
            for (int i = 0; i < amountAmount.length(); i++) 
            {
                if (!Character.isDigit(amountAmount.charAt(i)))
                    {
                        JOptionPane.showMessageDialog(null, 
                        "You must enter a number for amount invested.", 
                        "Investment Amount Error", JOptionPane.ERROR_MESSAGE);
                        return false;
                    }
            } 
     
            double dblAmount = Double.parseDouble(amountAmount);
     
            return true;
     
        }
        public static boolean inputYears()
        {
            String yearAmount = "";
     
            yearAmount = JOptionPane.showInputDialog(
                null, 
                "Enter the number of years to invest." , 
                "Investment Years" , JOptionPane.QUESTION_MESSAGE);
     
            if (yearAmount == null || yearAmount.length() == 0)
                {
                    JOptionPane.showMessageDialog(null, 
                    "Nothing entered - You must enter a number for years to invest.", 
                    "Investment Years Error", JOptionPane.ERROR_MESSAGE);
                    return false;
                }
     
            for (int i = 0; i < yearAmount.length(); i++) 
            {
                if (!Character.isDigit(yearAmount.charAt(i)))
                    {
                        JOptionPane.showMessageDialog(null, 
                        "You must enter a number of years to invest.", 
                        "Investment Years Error", JOptionPane.ERROR_MESSAGE);
                        return false;
                    }
            }
     
            double dblYear = Double.parseDouble(yearAmount);
     
            return true;
        }
    }

    I've looked over the code a few times and I'm not sure what is affecting this and forcing it to only use the default constructor. For example if I try to put in 2000 for the amount invested it will still default to 1000.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Only uses Default Constructor

    if I try to put in 2000 for the amount invested it will still default to 1000.
    can you copy the contents of the command prompt window that shows the input and output from the program?
    Add some comments to it that shows what is wrong with what the program does.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Only uses Default Constructor

    Here is where I should be putting in my input for example I choose for "invest" 2000 however the code won't read that and is navigating back to the default constructor
    investamount.jpg

    This is where I should be putting in the amount of years to invest which I choose to be 2 however it isn't being read and:
    investyears.jpg


    This shows the output of the default constructor of 1000 and outputs for 5 invested years in 5 separate dialog boxes as opposed to just one.
    output.jpg

  4. #4
    Junior Member
    Join Date
    Feb 2013
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Only uses Default Constructor

    I believe the problem I'm having for it only using the default constructor is that I can't pull the moneyInvested; and yearsInvested; because they are private classes:

    private double moneyInvested;
        private double yearsInvested;
     
        public final static double AMOUNT_DEFAULT = 1000;
        public final static double YEARS_DEFAULT = 5;
     
        public final static double RATE = 0.12;
     
        public Investment()
        {
            moneyInvested = AMOUNT_DEFAULT;
            yearsInvested = YEARS_DEFAULT;
        }
     
     
        public Investment(double AMOUNT_DEFAULT, double YEARS_DEFAULT)
        {
            if (moneyInvested <= 0)
            {
                moneyInvested = AMOUNT_DEFAULT;
            }
     
            if (yearsInvested <= 0)
            {
                yearsInvested = YEARS_DEFAULT;
            }
        }
     
        public double getMoneyInvested()
    	 {
    	 	return moneyInvested;
    	 }
        public double getYearsInvested()
    	 {
    	 	return yearsInvested;
    	 }

    and in my makeInvestment class it reads:

    public static void main(String[] args)
        {     
            Investment otherClass = new Investment(); 
            double yA = otherClass.YEARS_DEFAULT;
            double mA = otherClass.AMOUNT_DEFAULT;
     
            while (inputAmount() == false)
            {
                inputAmount();
            }
     
            while (inputYears() == false)
            {
                inputYears();
            }
     
            otherClass.returnValue(yA, mA);
     
        }

    but I can't unmake those private classes...

    --- Update ---

    So it's only reading the default

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Only uses Default Constructor

    How does the value you enter in the dialog window get to the code that computes the values that are printed out?

    Follow the code following the call to JOptionPane to see where the entered values go.

    In main() Where are the values of yA and mA changed after they are given the default values?

    How could the values that the user entered be used by the returnValue() method?

    Why are there possilby multiple calls to inputAmount()?

    Only uses Default Constructor
    That is what the code currently does. If it only calls the default constructor then the default values will be used.


    A problem with the code is the use of static in the Investment class. Nothing in the class should be static.


    Suggestion: Start over. Design the program before continuing to write more code in this program. There are many many design problems in this code. The methods do not do anything to help the class get the data and produce the desired results.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Feb 2013
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Only uses Default Constructor

    Aggg this code is bugging me horribly. I might try starting I think the biggest problem I'm having trouble understanding is setting the yearsInvested; and moneyInvested; to private but then having to call them in the makeInvestment class.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Only uses Default Constructor

    The posted code is a mess. I suggest you start over.

    Make a list of what the class needs to do. This list would be used to define the variables and methods needed in the class. There should NOT be any static variables or methods.

    Make a list of the steps the program should take to test the class. These steps would be used to write the code in the main method.

    Questions to resolve:
    Where to get the two numbers it needs to do the job?
    How and where to save the values it has read from the user?
    What method will generate the desired output?
    Where will that method get its input values from?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Member
    Join Date
    Feb 2013
    Location
    Canada
    Posts
    54
    Thanks
    0
    Thanked 6 Times in 6 Posts

    Default Re: Only uses Default Constructor

    Your code needs a lot of work in that some of it doesn't do what you want and other parts are written in a very unusual way. I think it's time to put those classes to the side and start over. I find it helpful to first think about what the program has to do. Next, draw out the contents of each class I'm going to make before I even start typing. For example:

    Class A

    ----------------------------------------------------------------
    - years : int
    - amount : double
    - INTEREST : double
    ----------------------------------------------------------------
    + setYears(newYears: int) : void
    -> sets years to newYears
    + getYears(years : int) : int
    -> return the value of years
    ---------------------------------------------------------------
    + A(years: int, amount: double) : years : int, amount : double
    -> passes in values for int and amount, then sets them
    + A() : years: int, amount : double
    -> no-argument constructor that sets all the data
    + toString() : String
    -> prints out a statement
    ---------------------------------------------------------------

    The first block contains all the field variables to be used in the class. All of the ones that start with a - indicate it is private. If it is in all capital letters, then it is a constant. The next section contains the methods to be used in the class. The last section contains the special set of methods, such as constructors and any methods that are to be overridden as denoted by underlining.

    I suggest you try something like this, obviously yours will include more than mine and for more than one class. Under each method, write what their purpose should be and how that relates to answering the questions.

    A few addition tips to keep in mind are your code should maximize reusability and think whether something actually makes sense. For example, if you're going to create a class asking how many dogs someone has, you're not going to use a double, boolean, float or String as they don't make sense.

Similar Threads

  1. HashMap Display Default value
    By naval.gupta4u@gmail.com in forum JavaServer Pages: JSP & JSTL
    Replies: 3
    Last Post: August 9th, 2012, 12:28 AM
  2. add a default constructor in abstract class
    By Kifli in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 8th, 2012, 12:42 AM
  3. which class has a default constructor? (Req. guidance on constructor)
    By DragBall in forum Java Theory & Questions
    Replies: 1
    Last Post: June 27th, 2012, 04:42 PM
  4. default Value of char
    By chronoz13 in forum Java Theory & Questions
    Replies: 2
    Last Post: September 12th, 2011, 09:25 AM
  5. [SOLVED] Class constructor default values
    By srs in forum Java Theory & Questions
    Replies: 3
    Last Post: November 25th, 2010, 09:51 PM