Link to home
Start Free TrialLog in
Avatar of Ansary100
Ansary100

asked on

inputs a set of int values

I am trying to Write code that inputs a set of int values and computes its average. I will aske the user first how many int values will be input.  Assume that the scanner class has been imported In java programming
Avatar of mathbiol
mathbiol

Ansary,

Sounds like you could use a for loop from 1 to numberValues (input by the user).

To compute the average, just keep accumulating the sum of the integer values as they are input.  Then when they've all been read in, divide by numberValues to compute the average.

This should be a pretty straightforward program.  The danger that I see is that you've got all integer input and you might be tempted to do division of an integer by an integer, which might give erroneous results.  It would be a good idea to convert (or cast) the integer-valued variables sum and numberValues to floating point for the purposes of doing division.

Does this get you unstuck?

mathbiol
Avatar of Ansary100

ASKER

Hi mathbiol
do you thank this what you suggest to answer this trouble

mport java.text.DecimalFormat;
import java.util.Scanner;

public class Average
{
 
   public static void main (String[] args)
   {
      int sum = 0, value, count = 0;
      double average;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter an integer (0 to quit): ");
      value = scan.nextInt();

      while (value != 0)  // sentinel value of 0 to terminate loop
      {
         count++;

         sum += value;
         System.out.println ("The sum so far is " + sum);

         System.out.print ("Enter an integer (0 to quit): ");
         value = scan.nextInt();
      }

      System.out.println ();

      if (count == 0)
         System.out.println ("No values were entered.");
      else
      {
         average = (double)sum / count;

         DecimalFormat fmt = new DecimalFormat ("0.###");
         System.out.println ("The average is " + fmt.format(average));
      }
   }
}
Ansary,

Well, I don't program in Java, but I can see that this program structure does not fit your problem description.

I recommend that you use a for loop, not a while loop.  Begin by inviting the user to give you numberValues.  Then loop from 1 to numberValues.  If you review an example of a for loop in your book, this will hopefully be clear.

I am glad to see that you initialized sum to zero.  Note that since the user is supposed to give you numberValues, you do not need to keep a count.

In your line
> average = (double)sum / count;
I wonder how that works.  To be safe, what you should be doing is casting sum to double and the denominator to double separately.  That would be most appropriate for doing floating point arithmetic.

mathbiol
Ansary,
you mention that you wish to prompt for the number of values to input, and then retrieve these numbers, etc..
This makes it a lot easier, because you can then use an array, and a for-loop.  :-)

Give this a go:


import java.util.*;
import java.text.*;

public class Average
{
   
    public static void main( String [] args )
    {
       
        Scanner s = new Scanner( System.in );
       
        int max = 0;
        System.out.print( "Enter the number of elements that you want to process: " );
       
        try
        {
            max = s.nextInt();
            if ( max < 1 )
                throw new Exception( "You must specify an integer, greater than 1!" );
        } catch ( Exception e )
        {
            e.printStackTrace( System.out );
        }
       
        int [] values = new int[max];
       
        try
        {
            for ( int i = 0; i < max; i++ )
            {
                System.out.print( "\nEnter an integer: " );
                values[i] = s.nextInt();
            }
        } catch ( Exception e )
        {
            e.printStackTrace( System.out );
        }
       
        double average = 0;
        for ( int i = 0; i < max; i++ )
            average += values[i];
       
        average /= 2;
       
        DecimalFormat fmt = new DecimalFormat ("0.###");
       
        System.out.println( "\n\nThe average: " + fmt.format(average) );
       
       
    }
   
}

Rob,

Other questions posed by Ansary100 suggest that he's just starting out with  programming.  Wouldn't he benefit more from guidance than from full code?  If he's interested in learning to write his own code, he'll do better if he actually writes code, rather than always reading what other people wrote, don't you think?

As I mentioned, he doesn't need an array.  He doesn't need to store values for later processing.  He can process them as he reads them in.  Thus he only needs one for loop.  There's nothing terrible about using an unnecessary array, but we would like him to learn good programming habits.

To calculate an average, you need to divide by the number of values in the list.  You seem to be dividing by two.  That would be appropriate only in the case of exactly two values.

For example, the average of these numbers
3
6
9
is (3 + 6 + 9) / 3 = 6
not (3 + 6 + 9) / 2 = 9

mathbiol
ASKER CERTIFIED SOLUTION
Avatar of InteractiveMind
InteractiveMind
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Rob,

Ohmygod.  This is like hitting a mosquito with a sledge hammer.  There are things you need a sledge hammer for, but a mosquito is not one of them.

Ansary100's exercise is a textbook example of how to get the hang of using a for loop.

A FOR LOOP

A FOR LOOP!

A while loop is not needed.

You do not need this line:
      number_of_elements++;
The number of elements is input by the user!  (I didn't write the specs.)

Thank you for getting rid of the array.

Can you move your exam date up so you'll stop procrastinating to avoid studying for them?

mathbiol