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 5 of 5

Thread: Loop Problem

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Location
    California, Bay Area
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Loop Problem

    Hey everybody

    I've been working on this code for almost half the day yesterday and need some help, and I'm very new to java so please excuse my blunders.

    before i came this forum i,
    -read the chapter ten times over
    -tried out different kinds of loops to solve my problem

    In my mind it does not seem possible to answer the question that my teacher gave me, but I might be missing something and if I am, please let me know
    (solved this part ^)

    THE PROBLEM
    __________________________________________________ ___________________
    You are tracking the prices of some assets overtime.
    The user will input a series of floating-point prices.
    When the user enters 0, output the overall minimum, mean, and maximum prices.
    __________________________________________________ ___________________

    I can produce a min, mean, and maximum now, but the minimum shows up as 0 because the user has to enter zero when finished entering prices! What would be a good idea to change it so that it wouldn't show up at 0?

    here is my code:Code 6.jpgCode 6x.jpg

    // This program prompts the user to input the prices of some assets overitme. When the user enters zero, the program outputs the minimum, mean$
    // HINT: keep a running total because there could be millions of prices to process
     
    import java.io.*; // Needed for the File and IOException
    import java.util.Scanner; // Needed for the Scanner Class
     
    public class assignment6
    {
            public static void main(String[] args) throws IOException
            {
     
            double price; // To hold store the asset prices
            int count = 1; // To hold the number of assets the user is tracking
            double totalPrices; // accumulator
            double minimum; // To hold the mininum asset price
            double mean; // To hold the mean of all the assets
            double maximum; // To hold the maximum asset price
     
     
            //Create a Scanner object for keyboard input.
            Scanner keyboard = new Scanner(System.in);
     
            //Creates instructions for the user
            System.out.println("Please enter the amount of assets you are tracking");
            System.out.println("and the price of each asset you are tracking");
            System.out.println("Enter 0 when finished.");
            System.out.println();
     
            //Prompts the user to insert price for assets
            System.out.println("Please enter the price for asset" +count+ " or enter 0 when finished: ");
            price = keyboard.nextDouble();
     
            totalPrices = 0.0; // Set the accumulator to zero
            mean = 0.0; // Set the mean to zero
            minimum = 0.0; // Set the minimum to zero
            maximum = 0.0; // Set the maximum to zero
     
            //Get the assets prices and calculate a running total.
            while(price != 0)
            {
     
            // Add price to totalPrices
            totalPrices +=price;
     
            // Get the price for the assets
            System.out.println("Please enter the price for asset" +count+ " or enter 0 when finished: ");
            price = keyboard.nextDouble();
            count++;
     
            //Calculates the minimum
            if(price < minimum)
            {
            minimum = price;
            }
     
            //Calculates the maximum
            if(price > maximum)
            {
            maximum = price;
            }
     
            // Calculate the mean
            mean = totalPrices / count;
     
            }
     
            // Displays mean, minimum, and maximum of asset prices
            System.out.println("The mean of your asset prices are " +mean);
            System.out.println("The mininum of your asset prices are "+ minimum);
            System.out.println("The maximum of your asset prices are "+ maximum);
     
            }
    }
    // Compiler, please let this java program run!!! I beg you D:
    Last edited by Wwong3333; September 30th, 2012 at 09:01 PM. Reason: Improved loop
    work hard, play hard.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Loop Problem

    Please edit your post and remove the profanity, as some find it offensive.

    Please post your code on the forum and use code tags. See the announcements if you do not know how.

    When you want to write code and don't know how to do it, that is usually a good sign that the problem can be broken down into smaller steps.

    So think it out. How would you solve the problem if you were the computer? I give you a series of numbers. You take them from me one at a time. How do you decide which number was the largest and which was the smallest? Keep track of the smallest and largest as I give you numbers?

  3. The Following User Says Thank You to jps For This Useful Post:

    Wwong3333 (October 1st, 2012)

  4. #3
    Junior Member
    Join Date
    Sep 2012
    Location
    California, Bay Area
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Loop Problem

    ah i'm sorry! i've read some other posts with profanity and thought it was a humorous thing to do, i'll remove it right away. Thanks for the reply, i'll think about what you just said now
    work hard, play hard.

  5. #4
    Junior Member
    Join Date
    Sep 2012
    Location
    California, Bay Area
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Loop Problem

    Quote Originally Posted by jps View Post
    Please edit your post and remove the profanity, as some find it offensive.

    Please post your code on the forum and use code tags. See the announcements if you do not know how.

    When you want to write code and don't know how to do it, that is usually a good sign that the problem can be broken down into smaller steps.

    So think it out. How would you solve the problem if you were the computer? I give you a series of numbers. You take them from me one at a time. How do you decide which number was the largest and which was the smallest? Keep track of the smallest and largest as I give you numbers?
    YAY!! i figured it out, using if, i could print out the maximum and minimum asset price inputted by the user. But I found a new problem . Thing is, I have to make the user input 0 when he/she finishes, and that 0 is used for the minimum value. 0 is an assertion that there is no more prices, not a value.
    work hard, play hard.

  6. #5
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Loop Problem

    Quote Originally Posted by Wwong3333 View Post
    YAY!! i figured it out
    That's a really big Yay! (Old-timers used to say, "Huzzah!")


    Quote Originally Posted by Wwong3333 View Post
    ... make the user input 0 when he/she finishes...
    Well, if you haven't figured out this part yet, try making the program tell you what it is seeing and what it is doing at each place where it makes a decision. Maybe something like:


    [Edit]Note that in a premature posting of this snippet, I had inadvertantly pasted duplicate pieces of code. Sorry. The intent was (and is) to use the same code as in the Original Post but with a couple of debugging print statements added.[/Edit]
             //Prompts the user to insert price for assets
            System.out.println("Please enter the price for asset" +count+ " or enter 0 when finished: ");
            price = keyboard.nextDouble();
     
            totalPrices = 0.0; // Set the accumulator to zero
            mean = 0.0; // Set the mean to zero
            minimum = 0.0; // Set the minimum to zero
            maximum = 0.0; // Set the maximum to zero
     
            //Get the assets prices and calculate a running total.
            while(price != 0)
            {
     
                // Add price to totalPrices
                totalPrices +=price;
     
                // Get the price for the assets
                System.out.println("Please enter the price for asset" +count+ " or enter 0 when finished: ");
                price = keyboard.nextDouble();
                count++;
     
                //Calculates the minimum
                if(price < minimum)
                {
                    // For debugging:
                    // Let the programmer know what it found
                    System.out.println("New minimum = " + price);
                    minimum = price;
                }
     
                //Calculates the maximum
                if(price > maximum)
                {
                    // For debugging:
                    // Let the programmer know what it found
                    System.out.println("New maximum = " + price);
                    maximum = price;
                }
                // From Zaphod_b: For debugging, why not print out the values
                // of total and count here so that you can see what it is using
                // when it calculates the mean?
     
                // Calculate the mean
                mean = totalPrices / count;
     
            }

    Here's a run. Program output is blue, user input (that's me) is black.

    Please enter the amount of assets you are tracking
    and the price of each asset you are tracking
    Enter 0 when finished.

    Please enter the price for asset1 or enter 0 when finished:
    100
    Please enter the price for asset1 or enter 0 when finished:
    50
    New maximum = 50.0
    Please enter the price for asset2 or enter 0 when finished:
    25
    Please enter the price for asset3 or enter 0 when finished:
    0
    The mean of your asset prices are 43.75
    The mininum of your asset prices are 0.0
    The maximum of your asset prices are 50.0


    Hmmm... what happened? It didn't get the maximum correct and it didn't get the minimum correct. It also didn't get the average correct. How could that happen?

    Since not a single output value is correct, should we throw it away and start all over again. Maybe that's the best thing in some programs that I have seen (and some that I have written), but not for this one. The sequence is correct, right? (Repeatedly asks for user input and terminates when the pre-defined sentinal value is encountered.) It gets answers; the only problem is that they are wrong. In other words, it's easier to fix something that's wrong than it is to fix nothing.

    Here's the thing: If a program has substantially correct behavior (starts and stops OK) but gives wrong outputs for some input sequences, then those are the easiest kind to debug. I mean the output is staring you in the face, but it's wrong. (Much harder are programs that act erratically or programs that go into infinite loops with stack overflow messages until they crash and stuff like that.)

    Bottom line: Your code is a pretty good start. Let's run with it.

    Anyhow...


    I'll get you started:
    Well, you set value of maximum to zero after the user had already entered the first value, so that one didn't participate in the comparison looking for the maximum value. Fix that one first. (You don't need to reorganize the program in any way unless you really want to. Just be more smarter in how you determine the maximum of all of the user input values.)

    My suggestion is that you not worry about the other discrepancies just yet. Maybe something will occur to you as you debug the first problem. In the meanwhile, just concentrate on one problem at a time. That's the ticket!

    If you make a change that gets the correct maximum value for the sequence of inputs in my example, try some more runs where values go up and down and back up and back down again. Make absolutely sure that the part that determines the max value is bullet-proof.

    Now that you have inspected the innards of the program to the extent of being able to fix the first thing, maybe other changes have occurred to you. Try them, one at a time. (Just make sure that subsequent fixes don't unfix the first one.)

    And so it goes...



    Cheers!

    Z
    Last edited by Zaphod_b; September 30th, 2012 at 04:20 PM.

  7. The Following User Says Thank You to Zaphod_b For This Useful Post:

    Wwong3333 (October 1st, 2012)

Similar Threads

  1. Problem with the loop ..... ;(
    By xcaldk74 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: February 29th, 2012, 01:25 PM
  2. [SOLVED] Problem with loop?
    By Rilstin81 in forum Loops & Control Statements
    Replies: 5
    Last Post: November 23rd, 2011, 07:48 PM
  3. [SOLVED] for loop problem
    By javaneedhelp in forum Loops & Control Statements
    Replies: 3
    Last Post: October 9th, 2011, 10:25 AM
  4. Problem with Loop
    By Dragonkndr712 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: February 8th, 2011, 12:12 PM
  5. [SOLVED] While Loop Problem :(
    By faisalnet5 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 10th, 2010, 11:23 AM