Wednesday, 15 July 2015

Java Programs Made Easy

Q)..A time input is received as stirng. Find if the hour format is in 12 hour format. the suffix am/pm is case insensitive.
input:"09:36 am"
output:true


  1. package Set1;
  2. import java.text.*;
  3. import java.util.*;
  4. public class ClassSet12 {
  5.  public static boolean hourFormat(String s) throws ParseException{
  6.   boolean b=false;
  7.   StringTokenizer st=new StringTokenizer(s," ");
  8.   String s1=st.nextToken();
  9.   String s2=st.nextToken();  
  10.   StringTokenizer st1=new StringTokenizer(s1,":");
  11.   int n1=Integer.parseInt(st1.nextToken()); 
  12.   int n2=Integer.parseInt(st1.nextToken()); 
  13.   if((s2.equalsIgnoreCase("am"))|| (s2.equalsIgnoreCase("pm")))
  14.    if((n1<=12)&&(n2<=59))
  15.     b=true; 
  16.   return b;
  17.  }
  18.  public static void main(String[] args) throws ParseException {
  19.   String s="19:36 am";
  20.   boolean b=hourFormat(s);
  21.   if(b==true)
  22.    System.out.println("the time is in 12 hr format");
  23.   else
  24.    System.out.println("the time is in 24 hr format");
  25.  }
  26. }