Advertisement
TheFastFish

number thing

Jan 7th, 2016
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class NumberThing {
  4.     //main method
  5.     public static void main(String[] args) {
  6.         int size, i;
  7.         int[] numbers;
  8.         boolean kill = false;
  9.         String choice;
  10.         Scanner input = new Scanner(System.in);
  11.  
  12.         System.out.print("Enter a size for the array: ");
  13.         size = input.nextInt();
  14.         numbers = new int[size];
  15.  
  16.         //random fill with numbers in range 0 - 99
  17.         for (i = 0; i < size; i++) {
  18.             numbers[i] = (int)(Math.random() * 100);
  19.         }
  20.  
  21.         while (!kill) {
  22.             System.out.print("\fEnter a letter to choose an operation:\n[S]um of array\n[A]verage of array\n[P]rint even indices\n[E]xit\nLetter? ");
  23.             choice = input.next().toUpperCase();
  24.  
  25.             switch (choice) {
  26.             case "A":
  27.                 System.out.printf("Average of array contents is %f\n", averageArray(numbers));
  28.                 break;
  29.             case "E":
  30.                 kill = true;
  31.                 break;
  32.             case "P":
  33.                 printEvenArray(numbers);
  34.                 break;
  35.             case "S":
  36.                 System.out.printf("Sum of array contents is %d\n", sumArray(numbers));
  37.                 System.out.print("Hit enter to continue");
  38.                 break;
  39.             }
  40.         }
  41.         input.close();
  42.     }
  43.  
  44.     //take the sum of all numbers in an array
  45.     public static int sumArray(int[] array) {
  46.         int i, sum = 0;
  47.  
  48.         for (i = 0; i < array.length; i++) {
  49.             sum += array[i];
  50.         }
  51.  
  52.         return sum;
  53.     }
  54.  
  55.     //return the average of all values in array
  56.     public static double averageArray(int[] array) {
  57.         return (double)sumArray(array) / (double)array.length;
  58.     }
  59.  
  60.     //print even-indexed elements of array
  61.     public static void printEvenArray(int[] array) {
  62.         int i;
  63.         for (i = 0; i < array.length; i += 2) {
  64.             System.out.println(array[i]);
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement