0

I have participated in a challenge, in which the requirement is to compare two time values t1 and t2, and print First if t1 occurs before t2 ; otherwise, print Second.

And, t1 != t2.

Sample Input:

2
10:19PM 02:49AM
08:49AM 09:10AM

Sample Output:

Second
First

My code:

import java.util.*;

public class Solution {

    static String timeCompare(String t1, String t2){
        // Complete this function

        String half1 = t1.substring(t1.length()-2); // gets AM/PM value
        String half2 = t2.substring(t2.length()-2);

        String time1 = t1.substring(0, t1.length()-2);
        String time2 = t2.substring(0, t2.length()-2);

        //System.out.println(time1);

        int hour1 = Integer.parseInt(time1.split(":")[0]);
        int hour2 = Integer.parseInt(time2.split(":")[0]);

        int min1 = Integer.parseInt(time1.split(":")[1]);
        int min2 = Integer.parseInt(time2.split(":")[1]);

        if(hour1 == 12) {
            hour1 = 0;
            //System.out.println(hour1);;
        }
        if(hour2 == 12) {
            hour2 = 0;
        }

        //System.out.println(hour1+" , "+hour2);

        if(half1.equals(half2)){
           // System.out.println(1);

            if(hour1 == hour2){

                if(min1 > min2){
                    return "Second";
                } 
                else{
                    return "First";
                }

            }
            else if(hour1 > hour2){
                return "Second";
            }
            else{
                //System.out.println(2);

                return "First";
            }

        }
        else if (half1 == "AM"){
            return "First";
        }
        else{
            return "Second";
        }

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String t1 = in.next();
            String t2 = in.next();
            String result = timeCompare(t1, t2);
            System.out.println(result);
        }
    }
}

I am not sure what am I doing wrong. But only 1 out of 10 test cases passed.

Can you tell what's wrong?

user63762453
  • 1,734
  • 2
  • 22
  • 44

2 Answers2

1

half1 == "AM" Here you have made a mistake. For String comparison , You need to use String#equals() method.

So change that line with half1.equals("AM"). This will do your work.

Sanket Makani
  • 2,491
  • 2
  • 15
  • 23
0

Refer to example here:

import java.time.LocalTime;
public class Main {
  public static void main(String[] args) {
    LocalTime t1 = LocalTime.of(10, 10, 0)
    LocalTime t2 = LocalTime.of(11, 11, 0);
    int result = t2.compareTo(t1); 
    if(result < 0){
       System.out.println("Second");
    }else if(result > 0 ){
       System.out.println("First");
    }else{
       System.out.println("Same Time");
    }
  }
}

The code above generates the following result:

Second

S Jayesh
  • 191
  • 1
  • 4
  • 19