Savant
Savant

Reputation: 31

How can I change my program to allow user input to take the time?

Im struggling on the project I set myself. I want the user to be able to input the time, but it needs to be legal (i.e if the time is 9:15 and they add 4 hours, it must be 01:15 Please help!

package time;

public class NewTime {

    int hh, mm;

    public NewTime(int hh, int mm) {
        if (hh > 0 && hh < 24 && mm > 0 && mm < 60) {

            this.hh = hh;
            this.mm = mm;

        }
    }

    public void addTime(int hh, int mm) {
        if (mm + this.mm > 59) {
            this.hh += mm / 60;
        }

        this.hh += hh;
        this.mm += mm;
    }
}

Upvotes: 0

Views: 88

Answers (3)

frontend_friend
frontend_friend

Reputation: 864

You might want to use the LocalDateTime API (added in Java 8).

LocalDateTime now = LocalDateTime.now();
LocalDateTime twoHoursFromNow = now.plusHours(2);

Getting user input of time requires parsing:

LocalDateTime inputTime = LocalDateTime.parse("2015-07-13T10:00:00");
LocalDateTime twoHoursFromInputTime = inputTime.plusHours(2);

This question may be a duplicate of Adding n hours to a date in Java?

Upvotes: 0

Blip
Blip

Reputation: 3171

Your problem lies here:

public void addTime(int hh, int mm) {
    if (mm + this.mm > 59) {
        this.hh += mm / 60;
    }

    this.hh += hh; //<--source of problem
    this.mm += mm;
}

You also need the check after all the addition whether the hh variable is more than 12. an if it is more than 12 deduct 12. So the corrected format would be:

public void addTime(int hh, int mm) {
    this.hh += hh;
    this.mm += mm;
    this.hh += this.mm / 60;
    this.mm = this.mm % 60; //This removes the problem where the mm may be 59 and this.mm is 2 
    this.hh = this.hh % 12; //This solves the problem of hour not getting over 12.
}

Here instead of checking whether the sum of this.mm and mm is greater than 59. We simply add the mm to this.mm and then add the integer division result of this.mm / 60 to hh. Also set the remainder of this integer division to this.mm. We repeat the same thing with hh to store only the remainder of the integer division of this.hh and 12 to give the output in the 12 hour format.

This should take care of your problem.

Upvotes: 1

Constuntine
Constuntine

Reputation: 508

I would suggest using the mod operator. When the user adds 4 hours. Use an if statement. If the new hour is greater than 12, then mod the new hour to get the correct time.

i.e.

 9:15 + 4 hours => 13:15
 13 % 12 => 1
 New time = 1:15

Upvotes: 0

Related Questions