• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 502
  • Last Modified:

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
0
Ansary100
Asked:
Ansary100
  • 4
  • 2
1 Solution
 
mathbiolCommented:
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
0
 
Ansary100Author Commented:
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));
      }
   }
}
0
 
mathbiolCommented:
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
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
InteractiveMindCommented:
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) );
       
       
    }
   
}

0
 
mathbiolCommented:
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
0
 
InteractiveMindCommented:
Oh, lol -- not sure why I used a two there, should be:

  average /= max;

but either way, that's a valid point from you, Mathbiol; but if we're getting into good programming habbits, then even for something as small as this, we should be demonstrating use of several methods (as in, class functions) and taking advantage of the style of OO, where as the style that both myself and Ansary produced is a bit, procedural-style.  :-)

So, I'll kind of do it in a more OO-friendly style ;-)


** How it's meant to be done **

First thing's first; design the software. When working with a small application, like this one, then just some simple pseudocode will do; perhaps just a flow-diagram. Make sure that you can make sense of the following:



            [Start]

              ||   <--------------------------------------
              \/                                                   /\
                                                                   ||
     Get integer from user                               ||
                                                                   ||
              ||                                                  ||
              \/                                                   ||

      Is the integer 0?   ->   No   ->   Add to temporary storage, and increment element count

              ||
              \/

              Yes

              ||
              \/

     More than 0 elements?

              ||
              \/
 
              Yes   ->   No   ->   [Finish]
 
              ||
              \/

Calculate, and then output the average

              ||
              \/

           [Finish]



Okay, now to turn this into code. Firstly, we're going to define the variables that will store the addition of all of the values inputted, and a second variable, which will store the number of values that have been inputted. That's what these two lines do:


    private int    number_of_elements = 0;
    private int    storage            = 0;


We now need to create a method, which will prompt the user for an integer, and return it. I've come up with this:


    public int getValue()
    {
        try
        {
            System.out.print( "\nEnter an integer (0 to break): " );
            return scan.nextInt();
        } catch ( Exception e ) {}
       
        return 0;
    }


Okay, what this will do, is output "Enter an integer (0 to break): ", then it will listen for an integer. Once an integer has been inputted, it will return it -- however, if the user inputs a value other than an integer, this will cause an exception to occur; the method will then, in this scenario, return 0.

Now, we also want a method, which will decide whether or not to calculate (and output) the Average. Iv'e come up with this:


    public boolean moreThanZeroElements()
    {
        return (number_of_elements > 0 );
    }


It will return true, if the user has inputted more than 0 elements, otherwise, it will return false.


So far, we have two methods; one which gets input from the user, and a second which will decide whether or not the user has inputted enough elements to calculate the average.. We now need a method, which will output the passed results, in a certain format. This seems fine to me:


    public void showResult( String result )
    {
        System.out.println( "\n\nThe average = " + result );
    }


Right; that's simple enough, agreed? Now, thinking ahead, I've decided that to avoid us having to call methods, with use of a dot-notated instance of the local class, like so:


   Average a = new Average();
   a.showResult(..);


(Which we will have to do, in order to call local methods in the main method (because it's static), I'm going to code everything inside the classes Constructor, so that I can call methods just like this:


   showResult(..);


I will then call the constructor, from the main() method, like so:


   new Average();


Okay. For the main code now:


        int temp;
        while ( (temp = getValue()) != 0 )
        {
            storage += temp;
            number_of_elements++;
        }

        if ( moreThanZeroElements() )
        {
            double average = storage / number_of_elements;
            DecimalFormat fmt = new DecimalFormat( "0.###" );
            showResult( fmt.format( average ) );
        }

        System.exit( 0 );


I think that this is all fairly self-explanatoray; but if not, then below is the full code, all put together, and fully-commented. See what you think:


/*
    Average.java
    This code may make more sense, and seem clearer, if viewed in a color-syntax IDE.
*/
import java.util.*;
import java.text.*;

public class Average
{
   
    /**
     *  This variable stores the number of integers, that the user has inputted.
     */
    private int     number_of_elements = 0;

    /**
     *  This variable is the sum, of all values that the user has inputted.
     */
    private int     storage            = 0;

    /**
     *  The Scanner instace; used to retrieve an integer from the user.
     */
    private Scanner scan               = new Scanner( System.in );
   
   
    /**
     *  The constructor; which will perform the operations you want it to.
     */
    public Average()
    {

        /**
         *  This variable is temporary. It will store the inputted value, during processing.
         */
        int temp;

        /**
         *  This while-loop will keep looping, while the return integer is not 0.
         */
        while ( (temp = getValue()) != 0 )
        {
            /**
             *  Add the inputted value to the storage variable.
             */
            storage += temp;

            /**
             *  Increment the number of elements that have been inputted.
             */
            number_of_elements++;
        }

        /**
         *  When it gets to this point, it means that the user has inputted a 0 (or an exception has occured).
         *  We know this, because it is only under those circumstances, that the above while-loop will break.
         */
       
        /**
         *  If the user has inputted at least 1 integer, then we need to calculate the average, and output it.
         */
        if ( moreThanZeroElements() )
        {
            /**
             *  Calculate the average, then call the showResult(double) method, to output it.
             */
            double average = storage / number_of_elements;
            DecimalFormat fmt = new DecimalFormat( "0.###" );
            showResult( fmt.format( average ) );
        }

        /**
         *  That's all that is necessary. So exit.
         */
        System.exit( 0 );
       
    }
   
    /**
     *  The main variable; entrance point to the application. Call the constructor, to perform the operations.
     */
    public static void main( String [] args )
    {
        new Average();
    }
   
   
    /**
     *  This method returns an integer, inputted by the user.
     */
    public int getValue()
    {
        try
        {
            System.out.print( "\nEnter an integer (0 to break): " );
            return scan.nextInt();                         // Return the value that the user inputted.
        } catch ( Exception e ) {}
       
        return 0;                                               // If an exception has occured, then return 0.
    }

    /**
     *  This method returns true, if the user has inputted more than 0 elements, otherwise, return false.
     */
    public boolean moreThanZeroElements()
    {
        return (number_of_elements > 0 );
    }

    /**
     *  This method outputs the value which is passed to it.
     */
    public void showResult( String result )
    {
        System.out.println( "\n\nThe average = " + result );
    }
   
}




I hope that helps a bit more!!  :-)

Rob.
0
 
mathbiolCommented:
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
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now