Guest User

Untitled

a guest
Oct 18th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. /**
  2. * Asks user to input their family's age and displays the average of the ages.
  3. *
  4. * @Laura
  5. * @1.0
  6. */
  7.  
  8. import java.util.*;
  9.  
  10. public class Age {
  11. public static void main (String[] args) {
  12. Scanner s = new Scanner(System.in); //initializing variables and ArrayList
  13. ArrayList<Integer> ages = new ArrayList<Integer>();
  14. String age = "";
  15. double average = 0.0;
  16. double sum = 0.0;
  17.  
  18. System.out.print("Enter your age: "); //prompts for age
  19. age = s.nextLine();
  20.  
  21. while (!checkIfStringIsNumber(age) || Integer.parseInt(age) < 0) { //catches if the age entered isn't a number or if the age entered is negative
  22. System.out.print("That is not a valid answer. Enter your age: "); //re-prompts
  23. age = s.nextLine();
  24. }
  25. ages.add(Integer.parseInt(age)); //converts age into an int and stores in the ArrayList
  26.  
  27. while (Integer.parseInt(age) > 0) { //exits loop if the age entered is negative
  28. System.out.print("Enter you family member's age. If you have no more family members, enter a negative number: "); //prompts for family member age
  29. age = s.nextLine();
  30. while (!checkIfStringIsNumber(age)) {
  31. System.out.print("That is not a valid answer. Enter your family member's age: ");
  32. age = s.nextLine();
  33. }
  34. if (Integer.parseInt(age) >= 0) { //if the age is positive, add it to the array
  35. ages.add(Integer.parseInt(age));
  36. }
  37. }
  38.  
  39. for (int i = 0; i < ages.size(); i++) {
  40. int temp = ages.get(i);
  41. sum += temp; //iterates through ages ArrayList and adds each item in ArrayList to the sum
  42. }
  43. average = sum/ages.size(); //divides the sum by the number of ages
  44. System.out.println("The average age of your family is " + average + "."); //outputs average age
  45. System.out.println("Program terminated.");
  46. }
  47. public static boolean checkIfStringIsNumber(String s) { //method to check if a string is a number
  48. try {
  49. Integer.parseInt(s);
  50. } catch (NumberFormatException e) { //if string isn't a number, return false
  51. return false;
  52. }
  53. return true;
  54. }
  55. }
Add Comment
Please, Sign In to add comment