Lesson 6.5 · Write it
Is it an hour?
A functionPython or Java12 tests, 8 of them hidden
On a phone? Put the lines in order instead
An alarm app asks for the hour to ring, on a 24-hour clock. Write a function that checks the text the user typed before the app uses it as an hour.
- Return
Truewhen the text is a whole number from 0 to 23, andFalsefor anything else (trueandfalsein Java). - Text that is not a whole number, such as a word, a decimal such as
7.5, or empty text, givesFalse. Your function must return, not stop with an error. - A whole number outside 0 to 23, such as 24 or -1, gives
False. - When the text is a whole number, it is from -1000 to 1000, written with digits and maybe a minus sign in front. There are no spaces.
Only the value your function returns is checked.
def valid_hour(text: str) -> bool
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- valid_hour("7") should return True: a whole number in the range (rule 1)
- valid_hour("seven") should return False: a word is not a whole number (rule 2)
- valid_hour("24") should return False: one past the last hour (rule 3)
- valid_hour("23") should return True: the last hour of the day (rule 1)
public static boolean validHour(String text)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- validHour("7") should return true: a whole number in the range (rule 1)
- validHour("seven") should return false: a word is not a whole number (rule 2)
- validHour("24") should return false: one past the last hour (rule 3)
- validHour("23") should return true: the last hour of the day (rule 1)