w3resource

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

Java Basic: Exercise-211 with Solution

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

Input:

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

Pictorial 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) {
        Scanner sc = new Scanner(System.in);
        int[] t = new int[8];
        System.out.println("Input the heights of eight buildings:");
        for(int i = 0; i < 8; i++){
            t[i] = sc.nextInt();
        }         
        Arrays.sort(t);
        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.

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?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH