w3resource

Java: Find heights of the top three building in descending order from eight given buildings


Find Top Three Building Heights

Write a Java program to find the heights of the top three buildings in descending order from eight given buildings.

Input:

0 ≤ height of building (integer) ≤ 10,000

Visual Presentation:

Java Basic Exercises: Find heights of the top three building in descending order from eight given buildings.

Sample Solution:

Java Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Creating a Scanner object for user input
        Scanner sc = new Scanner(System.in);

        // Array to store the heights of eight buildings
        int[] t = new int[8];

        // Prompting the user to input the heights of eight buildings
        System.out.println("Input the heights of eight buildings:");
        for (int i = 0; i < 8; i++) {
            t[i] = sc.nextInt();
        }

        // Sorting the array of building heights in ascending order
        Arrays.sort(t);

        // Displaying the heights of the top three buildings in descending order
        System.out.println("\nHeights of the top three buildings:");
        for (int i = 7; i >= 5; i--) {
            System.out.println(t[i]);
        }
    }
} 

Sample Output:

Input the heights of eight buildings:
 25 19 23 45 18 23 24 19

Heights of the top three buildings:
45
25
24

Flowchart:

Flowchart: Java exercises: Find heights of the top three building in descending order from eight given buildings.

For more Practice: Solve these Related Problems:

  • Write a Java program to find the top three unique building heights from a list that may contain duplicates.
  • Write a Java program to determine the top three building heights using a max heap for efficient retrieval.
  • Write a Java program to identify the three largest building heights from an unsorted array without fully sorting it.
  • Write a Java program to compute the top three building heights and also return their original indices in descending order.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to match any single character (use ?) or any sequence of characters use *) including the empty. The matching should cover the entire input string.
Next: Write a Java program to compute the digit number of sum of two given integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.