Java – Exam – Three largest Numbers

This trivial task was given at the SoftUni exam for Java. There are not  a lot of problems that I can solve, but this one was definitely one of them 🙂

Java_images

So, what is the input and what is the output? At first you are given a number (n), and then you are given n different numbers. As an output you should display the top 3 (or 2, if 2 numbers are given).

Input Output

20
50
100
10
75
100
75
50

It seems trivial, but it is not that easy… The problem is that the reverse sorting in Java is a little more complicated, e.g. Java does not support it as the normal one. After some research, I simply decided to do a small cheat, giving me 100% of the points. The cheat consists of the fact, that I actually do not need reverse sorting, as far as I already know that the highest number is at the last position – thus, my solution is quite unexpected … But it worked OK, so I was happy with it. A second difficult task at the solution was the fact that we should be able to sort decimal numbers as well. I do not know why, but using BigDecimal was a little strange for me, I was trying to use some float types, but things did not work out so well. Here is my working code:

From the other part, the original code is not so cheaty, thus they make it a little useful for many purposes. What they do different, is that they introduce a second loop, that actually prints the last three positions of the array. The idea for putting two conditions in a for loop was something that I really have not seen (yup!) and something definitely useful. Here is how it looks like:

Enjoy both codes 😀

Tagged with: , , ,