Solved Problem5 in java