Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

To build a program that has this feature: Requires the user to print integers,un

ID: 3622763 • Letter: T

Question

To build a program that has this feature:

Requires the user to print integers,until it's printed the value -9999 (sentinel)
which ends the cycle and is not part of the calculation.

It must be calculated how many numbers are printed, their sum and average.
The sum is not allowed to exceed the value 999999

 

 

 

This is what I have done so Far:

 

public class TestProg
{    public static void main (String[] args)  
        {    int myArray [];
            int sum = 0;
            int avg;

            /*
            *  code to populate the array
            */
           
            //for loop that walks through your array
            for (int i = 0; i < myArray.length(); i++)
            {    sum += myArray[i];
            }

            //Print out the sum
            System.out.println("Sum: " + sum);

            //Calculate the average
            avg = sum / myArray.length();

   }
}

Explanation / Answer

Using arrays to store the numbers is not only unnecessary, but inefficient.

import java.util.Scanner;

public class Numbers
{
      public static void main(String[] args)
      {
            // keyboard input
            Scanner kb = new Scanner(System.in);

            // variables to hold count and sum
            int count = 0;
            int sum = 0;

            // enter number until number is -9999
            while(true)
            {
                  System.out.print("Enter an integer: ");
                  int num = kb.nextInt();

                  // break condition
                  if(num == -9999)
                        break;
     
                  // increment count and update sum
                  count++;
                  sum += num;
            }

            // the sum can't exceed 999999
            if(sum > 999999)
                 
sum = 999999;

            // calculate average
            double average = sum/count;

            // print output
            System.out.println("Count: "+count);
            System.out.println("Sum: "+sum);
            System.out.println("Average: "+average);
      }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote