Solved Problem 4 in Java