Lab Assignment #3 :: CPTR 105 :: 03/20/09

  1. Write a program that will ask the student to input points scored on all assignments in a course during the semester. Accept as many numbers—assuming that these are double values—as the user enters as long as the numbers are non-negative (so stop accepting input as soon as the user enters a negative number). Your job is to calculate the sum and average of the points and display them to the user.

Solution

    import java.io.*;
    import java.util.Scanner;

    /**
    * Solution to lab assignment #3
    * Calculate the average and sum of non-negative numbers provided by the user
    */ 
    public class Tester {



        public static void main(String[] args) {

            Scanner kb = new Scanner(System.in);
            double sum = 0.0; // will use this for keeping track of the total
            int count = 0;

            System.out.println("Please enter a new grade: ");
            double number = kb.nextDouble(); // input the first number

            while (number >= 0) {
                count++;
                sum = sum + number;  // calculate the new total
                System.out.println("Please enter a new grade: ");
                number = kb.nextDouble(); // get a new number
            }

            System.out.println("The sum of the grades entered is " + sum);
            System.out.println("The average of the grades entered is " + sum / count);
        }
    }