Jump to content

How to implement the following loop in Java...

Marcus_Monteiro's Photo
Posted Jun 28 2011 09:53 AM
3146 Views

Hi guys,

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 :) .

Tags:
1 Subscribe


3 Replies

+ 2
  macnlos's Photo
Posted Jun 29 2011 06:46 AM

You are assuming that user has to type in a number and hit return, like this:

20 <return>
30 <return>
40 <return>

And you are trying to figure out a. how to provide them with repetitive prompts, and b. how to provide them a way to break out of the prompt.

Rather than approach this in a linear/serial fashion you might want to approach this way. Have the user input their series of numbers at one input, like this:

20 30 40 <return>

This removes the requirement of trying to figure out a prompt loop AND it makes it easier for the user to input a series of numbers.

Now the question is how to take input, which is "20 30 40", and figure out how to store it. I'm going to let you figure out how to get the input but let us assume that my example above is stored in a variable as follows:

String numSeries = "20 30 40";

I can take this string a create an Array using the Split method. The Split method basically looks for places to separate the whole string into pieces. Here is how it would look

String numSeriesArray[] = numSeries.Split(" ");

The "[]" on numSeriesArray tells Java you want to create an array.
The ".Split" on numSeries is a String method to split up the input on some delimiter.
The "(" ")" is the delimiter, which in this case is a space.

The resulting array would be as follows:

numSeriesArray[0] = 20
numSeriesArray[1] = 30
numSeriesArray[2] = 40

You can find some more information about this, it's where I dug it up, at:

http://www.artima.co...=1&thread=96632
=========================
Sent to you from my
iPad, iPhone, BlackBerry,
Laptop, Desktop, or
Kitchen Toaster
0
  Marcus_Monteiro's Photo
Posted Jun 30 2011 07:13 AM

Thanks @macnlos. I didn't know about Arrays (haven't got to this part of my book yet) and the insight of having the user input his series of numbers in one input was very helpful!
0
  mhalverson's Photo
Posted Jun 30 2011 11:31 AM

If arrays haven't been introduced, the author probably doesn't intend them to be used in this case.

One way is to use two variables, 'sum' and 'num', to store the sum of all the numbers and num to store the number of numbers entered. Each time a new number is entered, add it to sum and increment num by 1. Then you will simply calculate sum/num.