Question

Write a program that reads a string from the keyboard and tests whether it contains a...

Write a program that reads a string from the keyboard and tests whether it contains a valid time. Display the time as described below if it is valid, otherwise display a message as described below. The input date should have the format hh:mm:ss (where hh = hour, mm = minutes and ss = seconds in a 24 hour clock, for example 23:47:55).

Here are the input errors (exceptions) that your program should detect and deal with:
Receive the input from the user (give an example of the format you are expecting the user to use when entering the time) and check for the following:
⦁   missing one of parts (the hour or the minutes or the second is missing.
⦁   hh, mm or ss is not numeric
⦁   hh not between 0 and 23
⦁   mm is not between 0 and 59
⦁   ss is not between 0 and 59

Be specific when reporting an error. For example, “The input 24:04:20 contains an invalid hour of 24”.

If the user gives you invalid input, start the whole process again by asking the user for a valid time. Keep prompting the user until you get a valid time. A while (!valid) loop would work well here.

If the time is valid, then output a message in this format, “23:45:16 is 11:45:16 pm”. That is, convert it to the am/pm format.

The program should be coded as a series of method calls (within the try block, inside the while loop):
⦁   getInput( ) – asks the user for the time. Uses the String split( ) method to break it into 3 parts. Checks that there are 3 parts and throws a MissingColonException if there aren’t. The method returns the String array.
⦁   checkHour( ) – receives the hour String part of the array, tries to convert it to a numeric value, then checks if the number is between 0 and 23. Throws NumberFormatException and HourException
⦁   checkMinutes( ) – similar to checkHour( )
⦁   checkSeconds( ) – similar to checkHour( )

Notes:
⦁   Be sure that the output that you submit shows that your program has tested ALL the different types of errors that can occur.

⦁   The messages output by the catch blocks should be very specific. For example, output “24 is an invalid hour”, or “23:15 is missing one part”, rather than simply “invalid hour” or “invalid input”. The first 2 messages allow the user to better understand what input caused the problem; the other messages leave the user guessing about what the source of the problem is.

⦁   You do not need to write code for the NumberFormatException class; this already exists as part of Java.

⦁   You’ll need to write class definition files for the other exceptions described above.

⦁   Because Dr. Java does not show what the input is, you should write out the input before you do anything else (so that your professor can see what you entered).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here are the 3 classes

====================================================================================

public class HourException extends Throwable {
}

====================================================================================

public class MissingColonException extends Exception {

}

====================================================================================

import java.util.Scanner;

public class TimeValidator {

    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        while (true) {
            String militaryTime = "";
            try {
                militaryTime = getInput();
                String[] parts = militaryTime.split(":");

                boolean hourValid = false;
                try {
                    hourValid = checkHour(parts[0]);
                } catch (NumberFormatException nfe) {
                    System.out.println("The input " + militaryTime + " contains an invalid hour of " + parts[0]);
                } catch (HourException e) {
                    System.out.println("The input " + militaryTime + " contains an invalid hour of " + parts[0]);
                }
                boolean minuteValid = false;
                try {
                    minuteValid = checkMinutes(parts[1]);
                } catch (NumberFormatException nfe) {
                    System.out.println("The input " + militaryTime + " contains an invalid minutes of " + parts[1]);
                }
                boolean secondValid = false;
                try {
                    secondValid = checkSeconds(parts[2]);
                } catch (NumberFormatException nfe) {
                    System.out.println("The input " + militaryTime + " contains an invalid seconds of " + parts[2]);
                }

                if (hourValid && minuteValid && secondValid) {
                    String standardTime = convertToStandardTime(parts[0], parts[1], parts[2]);
                    System.out.println(standardTime);
                    break;
                } else {
                    continue;
                }

            } catch (MissingColonException e) {
                System.out.println("Time is not is correct format, colon missing");
            }

        }
    }

    private static String convertToStandardTime(String hours, String minutes, String seconds) {

        int hour = Integer.parseInt(hours);
        int minute = Integer.parseInt(minutes);
        int second = Integer.parseInt(seconds);
        String amPm = "am";
        StringBuilder buildTime = new StringBuilder();
        if (hour > 12) {
            amPm = "pm";
            buildTime.append((hour - 12)).append(":");
        } else if (hour < 10) {
            buildTime.append("0").append((hour)).append(":");
        } else {
            buildTime.append((hour)).append(":");
        }
        if (minute < 10) {
            buildTime.append("0").append(minute).append(":");
        } else {
            buildTime.append(minute).append(":");
        }
        if (second < 10) {
            buildTime.append("0").append(second);
        } else {
            buildTime.append(second);
        }

        buildTime.append(" ").append(amPm);
        return buildTime.toString();

    }

    private static boolean checkHour(String hours) throws HourException {


        int hour = Integer.parseInt(hours);
        if (0 <= hour && hour < 24) {
            return true;

        }else{
            throw new HourException();
        }


    }

    private static boolean checkMinutes(String mins) {

        int minutes = Integer.parseInt(mins);
        if (0 <= minutes && minutes < 59) {
            return true;
        }

        return false;
    }

    private static boolean checkSeconds(String secs) {

        int seconds = Integer.parseInt(secs);
        if (0 <= seconds && seconds < 59) {
            return true;
        }

        return false;
    }

    private static String getInput() throws MissingColonException {
        System.out.println("input date should have the format hh:mm:ss " +
                "(where hh = hour, mm = minutes and ss = seconds in a 24 hour clock, " +
                "for example 23:47:55): ");

        String militaryTime = sc.nextLine();
        if (militaryTime.contains(":")) {
            String[] timeParts = militaryTime.split(":");
            if (timeParts.length == 3) {
                return militaryTime;
            } else {
                throw new MissingColonException();
            }
        }
        throw new MissingColonException();
    }


}

====================================================================================

Add a comment
Know the answer?
Add Answer to:
Write a program that reads a string from the keyboard and tests whether it contains a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a Java console application that reads a string from the keyboard and tests whether it...

    Write a Java console application that reads a string from the keyboard and tests whether it contains a valid date. Display the date and a message that indicates whether it is valid. If it is not valid, also display a message explaining why it is NOT valid. The input date will have the format mm/dd/yyyy. A valid month value mm must be from 1 to 12 (January is 1). You can use: String monthPart = inputDate.substring(0, 2); int month =...

  • C Program Question 1: Write a program that reads a date from the keyboard and tests...

    C Program Question 1: Write a program that reads a date from the keyboard and tests whether it contains a valid date. Display the date and a message that indicates whether it is valid. If it is not valid, also display a message explaining why it is not valid. The input date will have the format: mm/dd/yyyy Note that there is no space in the above format. A date in this format must be entered in one line. A valid...

  • Question 1: Write a program in C that reads a date from the keyboard and tests...

    Question 1: Write a program in C that reads a date from the keyboard and tests whether it contains a valid date. Display the date and a message that indicates whether it is valid. If it is not valid, also display a message explaining why it is not valid. The input date will have the format: mm/dd/yyyy Note that there is no space in the above format. A date in this format must be entered in one line. A valid...

  • Python 3. Date Printer Write a program that reads a string from the user containing a...

    Python 3. Date Printer Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the format March 12, 2018 3. Date Printer Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the format March 12, 2018

  • Write a Java program that reads a series of strings from a user until STOP is...

    Write a Java program that reads a series of strings from a user until STOP is entered. Each input consists of information about one student at the ABC Professional School. The input consists of the student’s last name (the first 15 characters with extra blanks on the right if the name is not 15 characters long), the student’s number (the next 4 characters, all digits, a number between 1000 and 5999), and the student’s program of study (one character, either...

  • Python Write a program which reads in a string and an signifying the number times the...

    Python Write a program which reads in a string and an signifying the number times the string should be repeated. The program should then output the string N times. integer N, You can assume all input will be valid. Example: Enter a string: hello How many times to repeat? 5 hello hello hello hello hello Example: T Enter a string: goodbye Ty How many times to repeat? 32 goodbye goodbye [... goodbye 30 more times]

  • Write a program that reads a string from the keyboard and computes the two arrays of...

    Write a program that reads a string from the keyboard and computes the two arrays of integers upperCase, and lowerCase, each of size 26. The first one represents the frequency of upper case letters and the second one represents the frequency of lower case letters in the input string. After computing these arrays, the program prints the frequencies in the following format: The frequency of the letter A= The frequency of the letter B= Assume the input string contains only...

  • i need know how Write a program that tests whether a string is a valid password....

    i need know how Write a program that tests whether a string is a valid password. The password rules are: It must have at least eight characters. It must contain letters AND numbers It must contain at least two digits It must contain an underscore (_) Write a program that prompts the user to enter a password and displays the password entered and whether it is valid or invalid.

  • Write a program that reads a string from the user containing a date in the form...

    Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the format March 12, 2018   I am asking for help in basic python please

  • PLEASE WRITE CODE FOR C++ ! Time Validation, Leap Year and Money Growth PartA: Validate Day and Time Write a program tha...

    PLEASE WRITE CODE FOR C++ ! Time Validation, Leap Year and Money Growth PartA: Validate Day and Time Write a program that reads a values for hour and minute from the input test file timeData.txt . The data read for valid hour and valid minute entries. Assume you are working with a 24 hour time format. Your program should use functions called validateHour and validateMinutes. Below is a sample of the format to use for your output file  timeValidation.txt :   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT