Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class NumberThing {
- //main method
- public static void main(String[] args) {
- int size, i;
- int[] numbers;
- boolean kill = false;
- String choice;
- Scanner input = new Scanner(System.in);
- System.out.print("Enter a size for the array: ");
- size = input.nextInt();
- numbers = new int[size];
- //random fill with numbers in range 0 - 99
- for (i = 0; i < size; i++) {
- numbers[i] = (int)(Math.random() * 100);
- }
- while (!kill) {
- 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? ");
- choice = input.next().toUpperCase();
- switch (choice) {
- case "A":
- System.out.printf("Average of array contents is %f\n", averageArray(numbers));
- break;
- case "E":
- kill = true;
- break;
- case "P":
- printEvenArray(numbers);
- break;
- case "S":
- System.out.printf("Sum of array contents is %d\n", sumArray(numbers));
- System.out.print("Hit enter to continue");
- break;
- }
- }
- input.close();
- }
- //take the sum of all numbers in an array
- public static int sumArray(int[] array) {
- int i, sum = 0;
- for (i = 0; i < array.length; i++) {
- sum += array[i];
- }
- return sum;
- }
- //return the average of all values in array
- public static double averageArray(int[] array) {
- return (double)sumArray(array) / (double)array.length;
- }
- //print even-indexed elements of array
- public static void printEvenArray(int[] array) {
- int i;
- for (i = 0; i < array.length; i += 2) {
- System.out.println(array[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement