Time and hours in java

Viewed 65
import java.util.Scanner;

public class Nc3 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter time of arrival: ");
        double time = input.nextDouble();
        int arrivalTime;
        arrivalTime = 0;
        arrivalTime += time;

        if (time % 20 != 0) {
            time %= 20;
            time = 20 - time;
            System.out.println(arrivalTime +time);
        }

        else if (((arrivalTime + time) % 100) == 60.0) {
            time += 40;
            System.out.println(arrivalTime + time);
        }
        else
            System.out.println("Now - " +arrivalTime);

    }
}

I was asked to write a program that gets the input of the current time and give back the hour at which the next bus will leave knowing that a bus leaves every 20 minutes at 00, 20, 40 the problem is that if i input 2243 that represent 22:43 i will get back 2260 instead of 2300

1 Answers

java.time

I recommend you use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.

Demo:

import java.time.Duration;
import java.time.LocalTime;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter time of arrival: ");
        showNextDepartureTime(input.nextLine());
    }

    static void showNextDepartureTime(String arrivalTime) {
        Duration nextDeparture = Duration.between(LocalTime.MIN, LocalTime.parse(arrivalTime));
        int remainder = nextDeparture.toMinutesPart() % 20;
        if (remainder != 0)
            nextDeparture = nextDeparture.minusMinutes(remainder).plusMinutes(20);

        System.out.printf("The next departure is at %2d:%02d", nextDeparture.toHoursPart(),
                nextDeparture.toMinutesPart());
    }
}

A sample run:

Enter time of arrival: 22:43
The next departure is at 23:00

Another sample run:

Enter time of arrival: 22:00
The next departure is at 22:00

Update

As suggested by Lino in his comment, you can replace the if body as follows:

if (remainder != 0)
    nextDeparture = nextDeparture.plusMinutes(20 - remainder);
Related