javatimeuser-inputdatetime-comparison

Time comparision in java


I just get the time in HH:MM format and check if it is greater than 9:30 then count c is increased as 1.I just did for a single user input time.But i need to get multiple times from user and compare.If it is greater than 9:30 then increment the count values.First get n value and then get n no of time from user.How can i change my code to get the n no of time and compare that?

Scanner input = new Scanner(System.in);
 String time = input.nextLine();
 System.out.println();
 int c=0;
String time2 = "9:30";
 DateFormat sdf = new SimpleDateFormat("hh:mm");
 Date d1 = sdf.parse(time);
 Date d2 = sdf.parse(time2);
 if(d1.after(d2))
 {
     c++;
}
System.out.println(c);

Solution

  • This should do it. It is a basic implementation, you can optimize it the way you like.

    EDIT (with explanation comments):

    Scanner sc = new Scanner(System.in);
    
    // accept user input for N
    System.out.println("Enter N");
    int n = sc.nextInt();
    
    String time;
    int c = 0;
    
    // store the DateFormat to compare the user inputs with
    String time2 = "9:30";
    DateFormat sdf = new SimpleDateFormat("hh:mm");
    Date d2 = null;
    try {
        d2 = sdf.parse(time2);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    
    // iterate for N times, asking for a user input N times.
    for (int i = 0; i < n; i++) {
        // get user's input to parse and compare
        System.out.println("Enter Time");
        time = sc.next();
        Date d1 = null;
        try {
            d1 = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (d1.after(d2))  {
            c++;
        }
    }
    System.out.println(c);
    

    I have not changed much of your code, just added a loop and did the same thing for N times. To quote from the comments above, "loops are your friend".

    Hope this helps. Good luck. Comment if you have any further questions.