Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This code works, but it\'s missing the last part: \"If the user enters an illega

ID: 3865879 • Letter: T

Question

This code works, but it's missing the last part: "If the user enters an illegal time, like 10:65, or even gibberish, like 8&*68, your program should throw and handle a TimeFormatException." Could you add that?

Here'a the code. It works except for throwing an error when an incoorect time or character is entered.

Thank you,

import java.util.*;
public class C9PP1
{

public static void main(String[] args)
{
String time;
int hours,minutes;
//Scanner in=new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
String []temp;
char ampm;
do
    {
    System.out.print("Enter time in 24-hour notation: ");
    time=keyboard.nextLine();
  
    temp=time.split(":");
    hours=Integer.parseInt(temp[0]);
    minutes=Integer.parseInt(temp[1]);
    if(hours<12)
     ampm='A';
    else
    {
      ampm='P';
    hours-=12;

    }
    if(hours==0)
        hours=12;
    System.out.printf("That is the same as %d:%02d %cM ",hours,minutes,ampm);
    System.out.print("Again?(y/n) ");
     }
   while(Character.toUpperCase(keyboard.nextLine().charAt(0))=='Y');
}
}

Explanation / Answer

Here is modified class:

class C9PP1 {

Boolean check=false;

public static void main(String[] args)
{
String time;
int hours,minutes;
//Scanner in=new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
String []temp;
  
char ampm;
C9PP1 ob=new C9PP1();
do
{
System.out.print("Enter time in 24-hour notation: ");
time=keyboard.nextLine();
  
temp=time.split(":");
hours=Integer.parseInt(temp[0]);
minutes=Integer.parseInt(temp[1]);
try{
ob.check(hours,minutes);
  
}catch(Exception e)
{
System.out.println(""+e);
}
if(ob.check)
{
if(hours<12)
ampm='A';
else
{
ampm='P';
hours-=12;

}
if(hours==0)
hours=12;
System.out.printf("That is the same as %d:%02d %cM ",hours,minutes,ampm);
}
System.out.print("Again?(y/n) ");
}
while(Character.toUpperCase(keyboard.nextLine().charAt(0))=='Y');
}

void check(int hours,int minutes)throws InvalidTimeException{
if(hours>24||minutes>60)
{
check=false;
throw new InvalidTimeException("not valid");
  
}
else
{
check=true;
}
}

class InvalidTimeException extends Exception{
InvalidTimeException(String s){
super(s);
}
}
}

I'hv added custom time exception

I hope this solves your problem and comment if you have any problem in this code

And please dont forget to give thumbs up :)