Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class FindMaxAndMinInArray {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter size of the array: ");
- int sizeOfArray = Integer.parseInt(scan.nextLine());
- // Validate input. Size of array cannot be negative or equal to 0!
- while (sizeOfArray <= 0) {
- System.out.println("Size must be greater than 0!");
- System.out.print("Enter size of the array: ");
- sizeOfArray = Integer.parseInt(scan.nextLine());
- }
- // Initialize array with size!
- int[] numArray = new int[sizeOfArray];
- int sum = 0;
- for (int i = 0; i < numArray.length; i++) {
- System.out.printf("Enter integer # %,d: ", i+1);
- // Store number entered into array
- numArray[i]= Integer.parseInt(scan.nextLine());
- sum += numArray[i]; // add numbers entered
- }
- System.out.println("\nSUM: " + sum);
- System.out.printf("AVERAGE: %,.2f\n", ((double)sum / numArray.length));
- // Without using if-else, just sort the Array from smallest to largest
- // to find max and min
- Arrays.sort(numArray);
- System.out.println("MAX: " + (numArray[numArray.length-1]));
- System.out.println("MIN: " + (numArray[0]));
- // Using if-else to find max and min
- int largestInArray= numArray[0];
- int smallestInArray = numArray[0];
- for (int element : numArray) {
- if (largestInArray < element) {
- largestInArray = element;
- }
- if (smallestInArray > element) {
- smallestInArray = element;
- }
- }
- System.out.println("\nMAX: " + largestInArray);
- System.out.println("MIN: " + smallestInArray);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment