Problem 3 solved in Java