Created
August 12, 2018 18:24
-
-
Save kurtkaiser/0543f634a7af6a1b3b1dedf30c7e51bc to your computer and use it in GitHub Desktop.
This program allows the user to enter a time in 24-notation. The program throws an exception if the format or numbers are invalid. If no exceptions exist it converts the time and outputs it in 12-hour notation to the console. This was an assignment for an advanced java course at my local community college.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Kurt Kaiser | |
CTIM-168 | |
7/23/2018 | |
Convert Time | |
Chapter 9 - Project 1 | |
*/ | |
import java.util.Scanner; | |
public class ConvertTimeNotation { | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.print("Input a time in 24-hour notation: "); | |
String time = scan.next(); | |
try { | |
int colon = time.indexOf(":"); | |
if (colon < 0) | |
throw new TimeFormatException("Your input is not formatted correctly."); | |
int hour = Integer.parseInt(time.substring(0, colon)); | |
int minutes = Integer.parseInt(time.substring(colon + 1)); | |
if (hour <= 0 || hour > 24) | |
throw new TimeFormatException("Hours must be greater than 0 and less than 24."); | |
if (minutes <= 0 || minutes > 60) | |
throw new TimeFormatException("Minutes can not be less than 0 or 60 or greater."); | |
String ampm = "am"; | |
if (hour >= 12) { | |
ampm = "pm"; | |
hour = hour - 12; | |
} | |
System.out.print("In 12-hour notation: " + hour + ":" + minutes + ampm); | |
} | |
catch (TimeFormatException e) { | |
System.out.println(e.getMessage()); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Kurt Kaiser | |
CTIM-168 | |
7/23/2018 | |
Convert Time | |
Chapter 9 - Project 1 | |
*/ | |
public class TimeFormatException extends Exception | |
{ | |
public TimeFormatException(String message) { | |
super(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment