Results 1 to 4 of 4
  1. #1
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Location
    Miami, FL
    Posts
    47
    Rep Power
    0

    Post Stack is adding same values.

    Hello, in my application a series of inputs and a calculated result. At the end of each loop these inputs and calculations are displayed. After the loop is over with the user does not enter a string that is "y" or "Y", I want these inputs and the calculation to be displayed in a First in First Out format or a stack. I am using a LinkedList that is used in a class creating a stack.

    Here is the code for my stack.
    Java Code:
    import java.util.LinkedList;
    
    public class GenericStack<E> {
    
        LinkedList<E> stack = new LinkedList<>();
        
        public void Push(E element) {
            stack.addFirst(element);
        }
        
        public E Pop() {
            return stack.getFirst();
        }
        
        public int Size() {
            return stack.size();
        }
    }
    Here is the code containing the main method. The methods other than the main method are probably not relevant to the problem, but take a look if you like.
    Java Code:
    import java.util.*;
    import java.text.*;
    
    public class FutureValueApp
    {
        public static void main(String[] args)
        {
            GenericStack<String> stack = new GenericStack<>();
            
            // display a welcome message
            System.out.println("Welcome to the Future Value Calculator");
            System.out.println();
    
            // perform 1 or more calculations
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            while (choice.equalsIgnoreCase("y"))
            {
    
                // get the input from the user
                System.out.println("DATA ENTRY");
                double monthlyInvestment = getDoubleWithinRange(sc,
                    "Enter monthly investment: ", 0, 1000);
                double interestRate = getDoubleWithinRange(sc,
                    "Enter yearly interest rate: ", 0, 30);
                int years = getIntWithinRange(sc,
                    "Enter number of years: ", 0, 100);
    
                // calculate the future value
                double monthlyInterestRate = interestRate/12/100;
                int months = years * 12;
                double futureValue = calculateFutureValue(
                    monthlyInvestment, monthlyInterestRate, months);
    
                // get the currency and percent formatters
                NumberFormat currency = NumberFormat.getCurrencyInstance();
                NumberFormat percent = NumberFormat.getPercentInstance();
                percent.setMinimumFractionDigits(1);
    
                // format the result as a single string
                String results =
                      "Monthly investment:\t"
                          + currency.format(monthlyInvestment) + "\n"
                    + "Yearly interest rate:\t"
                          + percent.format(interestRate/100) + "\n"
                    + "Number of years:\t"
                          +  years + "\n"
                    + "Future value:\t\t"
                          + currency.format(futureValue) + "\n";
                
                    stack.Push(currency.format(monthlyInvestment) + "\t\t"
                    + percent.format(interestRate/100) + "\t\t"
                    + years + "\t"
                    + currency.format(futureValue));
    
                // print the results
                System.out.println();
                System.out.println("FORMATTED RESULTS");
                System.out.println(results);
    
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.next();
                System.out.println();
            }
            System.out.println("Montly Inv." + "\tInt. Rate" + "\tYears" + "\tFuture Value");
            
            for(int i = stack.Size(); i > 0; i--)
                System.out.println(stack.Pop());
            
        }
    
        public static double getDouble(Scanner sc, String prompt)
        {
            boolean isValid = false;
            double d = 0;
            while (isValid == false)
            {
                System.out.print(prompt);
                if (sc.hasNextDouble())
                {
                    d = sc.nextDouble();
                    isValid = true;
                }
                else
                {
                    System.out.println("Error! Invalid decimal value. Try again.");
                }
                sc.nextLine();  // discard any other data entered on the line
            }
            return d;
        }
    
        public static double getDoubleWithinRange(Scanner sc, String prompt,
        double min, double max)
        {
            double d = 0;
            boolean isValid = false;
            while (isValid == false)
            {
                d = getDouble(sc, prompt);
                if (d <= min)
                    System.out.println(
                        "Error! Number must be greater than " + min + ".");
                else if (d >= max)
                    System.out.println(
                        "Error! Number must be less than " + max + ".");
                else
                    isValid = true;
            }
            return d;
        }
    
        public static int getInt(Scanner sc, String prompt)
        {
            boolean isValidInt = false;
            int i = 0;
            while (isValidInt == false)
            {
                System.out.print(prompt);
                if (sc.hasNextInt())
                {
                    i = sc.nextInt();
                    isValidInt = true;
                }
                else
                {
                    System.out.println("Error! Invalid integer value. Try again.");
                }
                sc.nextLine();  // discard any other data entered on the line
            }
            return i;
        }
    
        public static int getIntWithinRange(Scanner sc, String prompt,
        int min, int max)
        {
            int i = 0;
            boolean isValid = false;
            while (isValid == false)
            {
                i = getInt(sc, prompt);
                if (i <= min)
                    System.out.println(
                        "Error! Number must be greater than " + min + ".");
                else if (i >= max)
                    System.out.println(
                        "Error! Number must be less than " + max + ".");
                else
                    isValid = true;
            }
            return i;
        }
    
        public static double calculateFutureValue(double monthlyInvestment,
        double monthlyInterestRate, int months)
        {
            double futureValue = 0;
            for (int i = 1; i <= months; i++)
            {
                futureValue =
                    (futureValue + monthlyInvestment) *
                    (1 + monthlyInterestRate);
            }
            return futureValue;
        }
    }
    The stack seems to be adding the same inputs and the same calculation from the first loop, even when it is on it's 2nd or third loop. I am getting this output.
    Java Code:
    Montly Inv.	Int. Rate	Years	Future Value
    $5.00		2.0%		5	$315.76
    $5.00		2.0%		5	$315.76
    Could someone help?

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,395
    Rep Power
    25

    Default Re: Stack is adding same values.

    First in First Out format or a stack
    It's queues that are FIFO, stacks are LIFO

    Can you explain what is wrong with the output and show what the output should be?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Location
    Miami, FL
    Posts
    47
    Rep Power
    0

    Default Re: Stack is adding same values.

    I actually solved this. Instead of using the get() method in my GenericStack class, I used the remove() method.
    The desired result is
    Java Code:
    Welcome to the Future Value Calculator
    
    DATA ENTRY
    Enter monthly investment: 42
    Enter yearly interest rate: 64
    Error! Number must be less than 30.0.
    Enter yearly interest rate: 2
    Enter number of years: 5
    
    FORMATTED RESULTS
    Monthly investment:	$42.00
    Yearly interest rate:	2.0%
    Number of years:	5
    Future value:		$2,652.40
    
    Continue? (y/n): y
    
    DATA ENTRY
    Enter monthly investment: 9
    Enter yearly interest rate: 5
    Enter number of years: 2
    
    FORMATTED RESULTS
    Monthly investment:	$9.00
    Yearly interest rate:	5.0%
    Number of years:	2
    Future value:		$227.62
    
    Continue? (y/n): y
    
    DATA ENTRY
    Enter monthly investment: 6
    Enter yearly interest rate: 2
    Enter number of years: 29
    
    FORMATTED RESULTS
    Monthly investment:	$6.00
    Yearly interest rate:	2.0%
    Number of years:	29
    Future value:		$2,831.35
    
    Continue? (y/n): n
    
    Montly Inv.	Int. Rate	Years	Future Value
    $6.00		2.0%		29	$2,831.35
    $9.00		5.0%		2	$227.62
    $42.00		2.0%		5	$2,652.40

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,395
    Rep Power
    25

    Default Re: Stack is adding same values.

    Good, mark this one as solved.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Adding new row kept previous row values.
    By jadeite100 in forum JavaServer Faces (JSF)
    Replies: 1
    Last Post: 05-21-2012, 07:47 PM
  2. Help adding array values.
    By Kirstielol in forum New To Java
    Replies: 4
    Last Post: 03-20-2012, 06:42 PM
  3. Replies: 0
    Last Post: 10-05-2010, 08:12 PM
  4. Adding Values of 2 Arrays
    By core2duo5252 in forum Java 2D
    Replies: 7
    Last Post: 09-05-2009, 03:50 AM
  5. BlackJack help please,, adding hand values
    By javakid9000 in forum New To Java
    Replies: 1
    Last Post: 11-18-2007, 04:26 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •