jasonpogi1669

Codio Exercises: Array (Exercise 5) from Summative Assessment 1

Jan 24th, 2021
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3.  
  4. public class Exercise5 {
  5.   public static void main(String args[]) {
  6.    
  7.     String input;
  8.     int total = 0;
  9.     double avg = 0;
  10.     ArrayList<Integer> numList = new ArrayList<Integer>();
  11.    
  12.     Scanner sc = new Scanner(System.in);
  13.     System.out.println("Enter integer to add to total, else find total average:");
  14.     while (sc.hasNextInt()) {
  15.       System.out.println("Enter integer to add to total, else find total average:");
  16.       input = sc.nextLine();
  17.      
  18.       // add input into ArrayList
  19.      
  20.       try {
  21.         numList.add(Integer.parseInt(input));
  22.       } catch(NumberFormatException e) {
  23.         System.out.println("Hello");
  24.         break;
  25.       }
  26.      
  27.       // your code goes above
  28.      
  29.     }
  30.    
  31.     // iterate through ArrayList, add elements to total, then calculate average
  32.    
  33.     for (int i = 0; i < numList.size(); i++) {
  34.       avg += numList.get(i);
  35.     }
  36.     if (numList.size() != 0) {
  37.       avg /= numList.size();
  38.     }
  39.    
  40.     // your code goes above
  41.    
  42.     System.out.println(avg);
  43.   }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment