In: Computer Science
ØWrite a method that takes a string representation of time in hours:minutes:seconds and returns the total number of seconds
•For example, if the input is “0:02:20” it would return 140
ØIf the input string is missing the hours component it should still work
•For example, input of “10:45” would return 645
ØWrite an overloaded form of the method that takes in only hours and minutes and returns the total number of seconds
•It should leverage the first method you wrote
•For example, an input of “2:05” should return 7205
ØLastly, write a method that takes seconds and returns a well-formatted time string, e.g., with two digits in each place
•For example, an input of 3666 would return “01:01:06”
import java.util.*;
public class Main
{
public static int TTS(int hour,int minute,int second){ //to solve
normal time format
int temp;
temp = second + (60 * minute) + (3600 * hour);
return temp;
}
public static int TTS(int hour,int second){ //to overload to
perform with special time cases
int temp;
temp = second + (3600 * hour);
return temp;
}
public static String sbr(int second1){ //to convert seconds to time
format
int p1 = second1 % 60;
int p2 = second1 / 60;
int p3 = p2 % 60;
p2 = p2 / 60;
String a="HH:MM:SS - " +p2 + ":" + p3 + ":" + p1;
return a;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String h="";
String[] h1;
System.out.println("Enter your
choice:\n1. Time in HH:MM:SS to Seconds\n2.Time in HH:SS to
Seconds\n3.Seconds to Time");
int d=sc.nextInt();
sc.nextLine();
switch(d){
case 1:
h=sc.nextLine();
h1=h.split(":");
int hour=0,minute=0,second=0;
if(h1.length==3){
hour=Integer.parseInt(h1[0]); //converting input string to
integers
minute=Integer.parseInt(h1[1]);//converting input string to
integers
second=Integer.parseInt(h1[2]);}//converting input string to
integers
else{
hour=00;
minute=Integer.parseInt(h1[0]);
second=Integer.parseInt(h1[1]);
}
int temp=TTS(hour,minute,second);
System.out.println("secondss :"+temp);
break;
case 2:
h=sc.nextLine();
h1=h.split(":");
hour=Integer.parseInt(h1[0]); //converting input string to
integers
second=Integer.parseInt(h1[1]); //converting input string to
integers
temp=TTS(hour,second);
System.out.println("secondss :"+temp);
break;
case 3:
int second1=sc.nextInt();
String c=sbr(second1);
System.out.println(c);
break;
default:
System.out.println("error");
break;
}
}
}
If you found this answer helpful please give a thumbs up.