Hi, I'm trying to write a method that uses a sentinel loop that repeatedly asks a user for input until a negative number is entered, and then prints the average.
I wrote the following code so far, but I can't figure out how to write an algorithm for the average? Any help is appreciated, thanks!
There are a couple things I would do with this method. You have some redundant code going on which can be eliminated by enclosing your prompt in a loop. This can be done several ways, one of which would be to declare a new variable and use it as your check to see if the loop continues also I would probably use an if/else construct not a while loop but that may just be preference. I am new here so I am not going to post code as I do not think it is allowed but to try to answer your original question you simply need to store your inputs in an ArrayList. Once your sentinel is entered call all of the elements in your ArrayList and do the average calculation. You will want to use an arraylist because it is a dynamic collection, meaning it grows in size as you need it to. So you will have an algorithm that calls all of your arraylist elements, adds them together and then divides that sum by the size of the arraylist. This is a very abridged version of what needs done, if you have never worked with collections let me know and I will do my best to explain it in more detail. If you need help with the actual code I will do all I can without violating the rules of this community.
Joined: Oct 18, 2011
Thank you so much for the detailed answer, but I'm in introductory Java in high school and we haven't learned array lists yet. Right now we're working with while loops, so I figured I should probably use those. I'm just having trouble figuring out how to write an algorithm to find the average. How can I set a value for the number of values entered by the user?
John C Stewart
Joined: Oct 24, 2011
If you mean to track how many responses have been entered before the sentinel and subsequent termination you would use a counter variable and increment it with each pass of the loop