Answer to Question #286175 in Java | JSP | JSF for Andrew

Question #286175

Write a program to store 25 numbers in an array. Then display those numbers divisible by 5 only in descending order using sorting and also display how many such numbers found.


1
Expert's answer
2022-01-10T07:38:38-0500
import java.util.InputMismatchException;
import java.util.Scanner;


public class Main {
    private static boolean divisibleByFive(int num) {
        return num % 5 == 0;
    }


    private static void doBubbleSort(int[] arr) {
        boolean sorted = false;
        int tmp;


        while (!sorted) {
            sorted = true;


            for (int i = 0; i < arr.length - 1; i++) {
                tmp = arr[i];


                if (tmp < arr[i + 1]) {
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;


                    sorted = false;
                }
            }
        }
    }


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);


        int arr[] = new int[25];
        int divisibleByFiveCounter = 0;


        System.out.println("Enter " + arr.length + " numbers:");
        for (int i = 0; i < arr.length; i++) {
            while (true) {
                try {
                    arr[i] = input.nextInt();


                    if (divisibleByFive(arr[i])) {
                        divisibleByFiveCounter++;
                    }
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("The entered number is incorrect, please try again...");
                    input.next();
                }
            }
        }


        if (divisibleByFiveCounter == 0) {
            System.out.println("No numbers divisible by 5 were found!");
            return;
        }


        int newArr[] = new int[divisibleByFiveCounter];
        int i2 = 0;
        for (int i = 0; i < arr.length; i++) {
            if (divisibleByFive(arr[i])) {
                newArr[i2] = arr[i];
                i2++;
            }
        }


        doBubbleSort(newArr);


        System.out.println("Found " + divisibleByFiveCounter + " numbers divisible by 5 (in descending order):");
        for (int i = 0; i < newArr.length; i++) {
            System.out.print(newArr[i] + " ");
        }
        System.out.println();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog