Problem 3 solution in java