1

We're looking at a clock through the mirror and I want to input what we see in the mirror and get the right clock. For example, the input is 3 55 and output (the actual time) is 09:05 with this conditions 0≤a≤11 0≤b≤59.

I wrote this code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a=scanner.nextInt() , b=scanner.nextInt();
        int h=(6-a)*2+a , m=(30-b)*2+b;
        System.out.printf("%02d:%02d",h,m);
    }
}

All inputs are OK except for 0 0. The output is 12:60 which is wrong.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
fa za
  • 31
  • 4
  • Interesting... 60 is a "correct" calculation, except that it's outside the range of your acceptable answers (I assume). Note that for 0 0, humans expect to take the larger value (12) for the hour, but the smaller value (0) for the minutes. You could add a `% 60` to the end of the calculation for `m` -- `m=((30-b)*2+b)%60`, i suppose. – Gus Aug 20 '21 at 15:41
  • 1
    @Gus But this will still allow things like `12:59`. I'd also simplify the calculation using some nifty math tricks: `(x-y)*2+y = 2x-2y+y = 2x-y`. Becomes: `h = 12-a` and `m = 60-b` – Benjamin M Aug 20 '21 at 15:44
  • I know he's allowed 0 0 as valid input, but I wouldn't assume that 12:59 is invalid; we'd have to get clarification from OP, but that's a time that I see almost daily on my digital clock :) Good catch on the simplified math. – Gus Aug 20 '21 at 15:50
  • 1
    oh, I just noticed, 12 isn't valid hour according to his input spec either, so we'd want the `%12` for the hour result too: `h=(12-a)%12` – Gus Aug 20 '21 at 15:52

1 Answers1

1

java.time

I would use the standard java.time API to avoid too many error-prone complex calculations.

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt(), b = scanner.nextInt();

        if (a >= 0 && a <= 11 && b >= 0 && b <= 59) {
            if (a == 0)
                a = 12;
            if (b == 0)
                b = 60;

            LocalTime time = LocalTime.of(12 - a, 60 - b);
            System.out.println(time);
        }
    }
}

A sample run:

3
55
09:05

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110