0

I am a noob programmer learning Java by myself and I have met with the following problem in one of the exercises:

// Ask the user to input as many numbers as he likes. Then calculate those numbers average.

Could somebody give me a hint of how I am supposed to do that? The best I thought so far is to ask the user to input some command to get out of the loop. But how can I store the inputs?

Thanks for your time and your help!

4
  • 1
    storing-wise you can use ArrayList or any other collection since mean doesn't care of the order. A command to end the input is fine. Good luck (and hopefully you are in the early teens) Commented Jun 28, 2011 at 18:06
  • @bestsss Thanks for the ArrayList hint, some people mentioned it too in their answers and I had no clue about Arrays (didn't get to this part of my book yet). And yes, I am in my early teens, so I still have plenty of time to learn (and build the next "Facebook", hehehe). Commented Jun 30, 2011 at 15:06
  • 1
    Google is beating you on the next facebook, hurry up :) Commented Jun 30, 2011 at 16:38
  • well, I am horribly older compared to you, I started off when I was 6, having a dream is fine however I'd advise you not to think of how huge projects you'd manage, instead concentrate at what you like the most (I know it's girls...) Commented Jun 30, 2011 at 17:08

8 Answers 8

2

Although you could use an ArrayList of Integers: ArrayList<Integer> that is quite excessive for this short problem.

Ideally, you could keep track of 2 int's, one containing the number of entries, and another the total sum.

int counter = 0;
int sum = 0;

When the user enters a new number, simply do the following:

counter++;
sum = sum + [the number entered]

and when the user is done entering numbers, return this value of

sum / counter;

an empty input could signal then end of number submission. So while looping, check to see if the string input is null or empty:

if(input == null || input.equals("")){
    // finish up and break out of the loop
}
Sign up to request clarification or add additional context in comments.

10 Comments

What if you have a huge number of integers? You'll overflow easily.
He said they would be inputted manually. It would take quite some time to overflow the counter.
The sum could just check before each new number was added.
it's easier to have a double that stores the average so far and then the number n of integers seen. Then, when there's a new integer, do the following: n++; average = average / n * (n-1) + number / n;. Dunno about numerical stability of such approach :)
Any overflow problems with this approach would be at least as bad, if not worse, with the approaches that needlessly create a container. If there are too many numbers, those approaches also risk running out of memory.
|
2

Actually you don't need to even store those numbers individually.

First let your user know that entering a blank line will indicate end of inputs.

Then have a variable called long total (or BigInteger) and keep running total of the numbers in that variable and keep a count of entered numbers in variable count as counter.

Once you're done reading all the inputs just output the average as total/count where count is total # of numbers entered by the user.

You can use Java scanner to read numbers from input.

Comments

2

Yes you would need the user to enter something to break from the loop. For example:

ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);

while(true)
{
    int num = input.nextInt();

    if(num == -1)
       break;

    list.add(num); // add number entered to list
}

The above uses the Scanner class and ArrayList class.

Alternatively you could do:

ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);

while(true)
{
    int num = input.next();

    if(num.equals("exit"))
       break;

    list.add(Integer.parseInt(num)); // convert String to Integer and add number entered to list
}

This uses Strings rather than Integers and may be more useful if any number can be accepted therefore you can't use it to break from the loop.

3 Comments

He asked for a hint. That is hardly a hint
I was just showing the possible ways that it can be done. If he is a beginner at programming I find they often need more of a steer in the right direction and it shows good coding habits.
Thank you AdamJMTech. I will study about Arrays and the Scanner class. I am not a begginer programmer, I am a NOOB programmer, hehehe. Hope I will get better.
1

You should use an ArrayList<Integer>.

Call the add() method to add numbers to it.

Comments

1

If you need the numbers afterwards, then follow SLaks' suggestion and store them in an ArrayList. You can find the official documentation for an ArrayList here.

However, if all you need is the sum, then just keep track of the "running sum" as the user inputs the numbers. Clearly there needs to be some kind of message from the user to the program to signal that he/she is done inputting (the alternative is to ask the user how many numbers are going to be inputted beforehand).

int sum = 0;
String s;

while( !( s = in.readLine() ).equals( "stop" ) )
    sum += Integer.parseInt( s );

Comments

1

You don't have to store the integers somewhere: you can just keep a sum of the integers seen so far and how many integers you've seen, and then return the fraction between the two numbers.

If you want to store them anyway, use whichever implementation of List interface you want to use.

Of course you have to take care of possibile integers overflows on both solutions. With the "store all integers first, then compute the average" is easier (you can loop over the array, summing element / size to the computed average), but you can take care of it even with the other approach; for example:

while (true) {
  num = readInteger();
  n++; 
  average = average / n * (n-1) + num / n;
}

2 Comments

I hope you are using something like a float here, integers won't exactly get you the result you need. Might be even better to calculate the result at the end of the loop (i'll add that to my answer).
well, I think it's obvious enough ;)
1

Use a while (true) {} loop to enter the number. When the user input the final number (for exampe, he enters a letter), quit from the loop using break.

Edit: No need to store all input numbers. Just add them all to one integer, and store the loopcount in another integer. After the loop, you do result = total / loops

int total = 0, loops = 0, result;
while (true) {
    String tmp = getInput();
    if (tmp.equals("q")) {
        break;
    }
    total += Integer.parseInt(tmp);
    loops++;
}
result = total / loops;

2 Comments

Thank you Dorus, but I will need the inputs so I can later print so I can print "The average of x, y and z is: ".
In that case add a line of code to add the int to a ArrayList too, as suggested by half a dozen of other users ;) You still need this part of the code to get the average. Once you're done you can use print() to print the first part of your sentence, and then make a loop to add the content of the arrayList(). Use println() at the end.
0

You can also ask the user for the number of elements(n) before the loop. Initialize an Array of that size(n) and use a for from 0 to n to input the numbers and save them into the array. This way you don't have to wait for the 'exit' command although you wont be able to enter more numbers than the ones you specified before.

1 Comment

Thanks for the insight of using Arrays. I will remember that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.