Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Asks user to input their family's age and displays the average of the ages.
- *
- * @Laura
- * @1.0
- */
- import java.util.*;
- public class Age {
- public static void main (String[] args) {
- Scanner s = new Scanner(System.in); //initializing variables and ArrayList
- ArrayList<Integer> ages = new ArrayList<Integer>();
- String age = "";
- double average = 0.0;
- double sum = 0.0;
- System.out.print("Enter your age: "); //prompts for age
- age = s.nextLine();
- while (!checkIfStringIsNumber(age) || Integer.parseInt(age) < 0) { //catches if the age entered isn't a number or if the age entered is negative
- System.out.print("That is not a valid answer. Enter your age: "); //re-prompts
- age = s.nextLine();
- }
- ages.add(Integer.parseInt(age)); //converts age into an int and stores in the ArrayList
- while (Integer.parseInt(age) > 0) { //exits loop if the age entered is negative
- 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
- age = s.nextLine();
- while (!checkIfStringIsNumber(age)) {
- System.out.print("That is not a valid answer. Enter your family member's age: ");
- age = s.nextLine();
- }
- if (Integer.parseInt(age) >= 0) { //if the age is positive, add it to the array
- ages.add(Integer.parseInt(age));
- }
- }
- for (int i = 0; i < ages.size(); i++) {
- int temp = ages.get(i);
- sum += temp; //iterates through ages ArrayList and adds each item in ArrayList to the sum
- }
- average = sum/ages.size(); //divides the sum by the number of ages
- System.out.println("The average age of your family is " + average + "."); //outputs average age
- System.out.println("Program terminated.");
- }
- public static boolean checkIfStringIsNumber(String s) { //method to check if a string is a number
- try {
- Integer.parseInt(s);
- } catch (NumberFormatException e) { //if string isn't a number, return false
- return false;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment