Advertisement
K_Wall_24

MarksAverager

Nov 21st, 2012
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3.  
  4. public class MarksAverager3
  5. {
  6.  
  7. public static void main(String[] args)
  8. {
  9.  
  10. // Display a title or description
  11. System.out.println("The Marks Averager (version 3)\n");
  12. System.out.println("Enter all your marks and then enter a negative mark to finish...\n");
  13.  
  14. // Create a Scanner object for obtaining user inputs
  15. Scanner input = new Scanner(System.in);
  16.  
  17. // Create an ArrayList to hold ALL the marks, each mark is type Double
  18. // Note that 'Double' is like 'double' except it's an object instead of a primitive
  19. ArrayList<Double> marksArray = new ArrayList<Double>();
  20.  
  21. // Loop to enter marks
  22. double mark;
  23. do
  24. {
  25. System.out.print("Enter another mark: ");
  26. mark = input.nextDouble();
  27.  
  28. if( mark >= 0 )
  29. {
  30. // Not the sentinel value, so add this mark to the ArrayList
  31. marksArray.add( mark );
  32. }
  33.  
  34. } while( mark >= 0 );
  35.  
  36. // Report the number of marks
  37. System.out.println("\nYou've entered " + marksArray.size() + " marks.");
  38.  
  39. // Calculate and report the average
  40. double total = 0;
  41. for(int i = 0; i < marksArray.size(); i++)
  42. {
  43. total += marksArray.get(i); // Gets the element at index i
  44. }
  45. double average = total / marksArray.size();
  46. System.out.println("The average mark is " + average + ".");
  47.  
  48. // Close the Scanner object
  49. input.close();
  50. }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement