Solved Problem 5 in Java