Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.ArrayList;
- public class MarksAverager3
- {
- public static void main(String[] args)
- {
- // Display a title or description
- System.out.println("The Marks Averager (version 3)\n");
- System.out.println("Enter all your marks and then enter a negative mark to finish...\n");
- // Create a Scanner object for obtaining user inputs
- Scanner input = new Scanner(System.in);
- // Create an ArrayList to hold ALL the marks, each mark is type Double
- // Note that 'Double' is like 'double' except it's an object instead of a primitive
- ArrayList<Double> marksArray = new ArrayList<Double>();
- // Loop to enter marks
- double mark;
- do
- {
- System.out.print("Enter another mark: ");
- mark = input.nextDouble();
- if( mark >= 0 )
- {
- // Not the sentinel value, so add this mark to the ArrayList
- marksArray.add( mark );
- }
- } while( mark >= 0 );
- // Report the number of marks
- System.out.println("\nYou've entered " + marksArray.size() + " marks.");
- // Calculate and report the average
- double total = 0;
- for(int i = 0; i < marksArray.size(); i++)
- {
- total += marksArray.get(i); // Gets the element at index i
- }
- double average = total / marksArray.size();
- System.out.println("The average mark is " + average + ".");
- // Close the Scanner object
- input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement