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 th开发者_JAVA技巧e inputs?
Thanks for your time and your help!
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
}
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.
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.
You should use an ArrayList<Integer>
.
Call the add()
method to add numbers to it.
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 );
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;
}
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;
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.
精彩评论