Solved Problem 6 in Java