Question

This lab will create a digital clock based on nested FOR loops for hours, minutes, and...

This lab will create a digital clock based on nested FOR loops for hours, minutes, and seconds, and a WHILE loop for doing over and over so that your clock works for all year long without interruption.

Note: If a group of students is interested, we could create a real digital wall-mounted clock to be placed in our classroom, so I can keep track of the time during my lectures. The actual clock would be based on the LED Strip used by Emma a couple of lectures ago. I would help you guys all the way through. Let me know if any of you would be interested in taking this challenge but fun project. See example of what I am talking about here.

2. Program Functional Requirements

2.1. Input Requirements

Your program shall request five inputs at startup:

  • Current hour
  • Current minute
  • Current seconds
  • Period of the day: “am” or “pm”
  • Day of the week: “Monday, Tuesday, …, Sunday”

2.1.1. Input Validation

Your program shall validate all the inputs as described below:

  • Valid hours: from 1 to 12
  • Valid minutes: from 0 to 59
  • Valid seconds: from 0 to 59
  • Valid periods: only “am” and “pm”, nothing else
  • Valid days of the week: well, you know what is valid here, right? (the user can enter upper case, lower case, or a mix of cases and your program should accept them without any problem (ex.: Sunday, sunday, and SUNDAY are valid inputs)

To simply your program, the validation can be performed after the user enter al the inputs. If any of the inputs above is not valid, your program shall:

  • Display a dialog box letting the person know that the given input (show the invalid input) is not valid and the valid values for the given input are (show the allowed values for that given input).
  • Request a new number

2.2. Program Logic Requirements

Only after the four inputs have been entered and validated your program should the following steps.

2.2.1. Display the Time

The following statement should be displayed in the terminal window every past second:

Day of the week hh:mm:ss am/pm

Example:

Saturday 11:50:04 pm

Where the first line displayed by your program should be the actual time that the user has entered in Section 2.1 above. (Pay attention that for values less than 10, your program must put a zero (0) at the front of the number, such as 04 in the example above).

Hint: you do not need to initialize the FOR loop with a hard-code value of 0. Instead you can initialize that variable with some other variable. See Example below:

for (int banana = 0; banana < 1000; banana++)

for (int banana = variable1; banana < 1000; banana++)

This will help to get your digital watch to display the right time as the program starts. However you must do some trick later on so that when the seconds (or minutes, or hours) goes to its maximum value (i.e., 59 seconds) the loop starts again from 0 and not “initial” value of variable1 (hum, you may change the value of variable1 when you reach 59 seconds to zero!)

2.2.2. Pause the program execution for 1 second

Use Thread.sleep(1000) to make your program wait for one thousand milliseconds (what is equivalent to 1 second) before printing another time stamp in the terminal window.

Please not that Java Virtual Machine takes some time (few microseconds) itself to process the for loops, and the printout statements, so you should really use a number slightly less than 1000 milliseconds to compensate this extra time that JVM spends doing other things. By How much? You can check how long JVM took from one print statement to the next one and then figure out how many milliseconds you need to subtract from 1000.

How would you possibly know how to do it???? Talking to your best programming friend: the internet. I talked to it and “he” gave me the following suggestion:

import java.time.*
Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis();

Try to adapt the code above into your own program. If you get stuck, ask the lab TA or your tall, young, handsome instructor…

2.2.3. Endless program

Remember your program when reaches midnight on Sunday it should keep going to the next week and so on.

3. Test Your Program

Even though the time you will be testing is not close to midnight, test your program giving the following initial inputs:

  • Sunday
  • 11 hours
  • 58 minutes
  • 15 seconds
  • pm

and wait until it reaches midnight and see if it goes to Monday, 12:00:00 am. Repeat this with 12h, 58m, and 15s and see if it goes from 12h to 1h when the hour is up.

4. Java Topics Used In this Lab

  • variable creation (int, boolean, etc.)
  • Nested FOR Loops
  • IF-ELSE statements
  • SWITCH Statements
  • Logical operators (AND, OR, and NOT)
  • WHILE loops
  • JOptionPane Input and Message dialog boxes
  • Input validation
  • Java API Thread
  • Java API DecimalFormat
  • Handling Exception
  • Java Imports
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi Friend

Here is the complete code in Java. Refer the screenshot for the sample output i ran where the time changed at midnight from Sunday to Monday, PM to AM : )

__________________________________________________________________________________________________

import java.util.Scanner;

public class DigitalWatch {

    private static String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        int hour = getHour();
        int minute = getMinutes();
        int second = getSeconds();
        String ampm = getPeriod();
        int dayIndex = getWeekDay();

        while (true) {

            if (second == 60) {
                second = 1;
                minute += 1;
                if (minute == 60) {
                    minute = 0;
                    hour += 1;
                    if (hour == 12) {
                        hour = 0;
                        ampm = ampm.equals("AM") ? "PM" : "AM";
                        if (ampm.equalsIgnoreCase("AM")) {
                            dayIndex = (dayIndex + 1) % 7;
                        }
                    }
                }
            } else {
                second += 1;
            }
            System.out.println(days[dayIndex] + " " +
                    (hour < 10 ? ("0" + hour) : hour) +
                    ":" +
                    (minute < 10 ? ("0" + minute) : minute) +
                    ":" +
                    (second < 10 ? ("0" + second) : second) + " " +
                    ampm);

            goToSleep(1000);
        }


    }

    private static void goToSleep(int millseconds) {
        try {
            Thread.sleep(millseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static int getHour() {
        while (true) {
            System.out.println("Enter hours 1 to 12:");
            int hour = scanner.nextInt();
            if (0 < hour && hour < 12) {
                return hour;
            } else {
                System.out.println("Valid hours: from 1 to 12");
            }

        }

    }

    public static int getMinutes() {
        while (true) {
            System.out.println("Enter minutes 0 to 59:");
            int mins = scanner.nextInt();
            if (0 < mins && mins < 60) {
                return mins;
            } else {
                System.out.println("Valid minutes: from 0 to 59");
            }

        }

    }

    public static int getSeconds() {
        while (true) {
            System.out.println("Enter seconds 0 to 59:");
            int secs = scanner.nextInt();
            if (0 < secs && secs < 60) {
                return secs;
            } else {
                System.out.println("Valid seconds: from 0 to 59");
            }

        }

    }

    public static String getPeriod() {
        while (true) {
            System.out.println("Enter period "am" or "pm": ");
            String ampm = scanner.nextLine();
            if (ampm.equalsIgnoreCase("am") || ampm.equalsIgnoreCase("pm")) {
                return ampm;
            } else {
                System.out.println("Valid periods: only "am" and "pm"");
            }

        }

    }

    public static int getWeekDay() {
        while (true) {
            System.out.println("Enter valid day of a week: ");
            String day = scanner.nextLine();
            for (int index = 0; index < days.length; index++) {
                if (day.trim().equalsIgnoreCase(days[index])) {
                    return index;
                }
            }
            System.out.println("Enter a valid day");
            continue;

        }

    }

}

________________________________________________________________________________________________

thank you !

please a thumbs up : )

Add a comment
Know the answer?
Add Answer to:
This lab will create a digital clock based on nested FOR loops for hours, minutes, and...
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
  • Need help creating a basic java string program using nested if/else, return loops or while loops...

    Need help creating a basic java string program using nested if/else, return loops or while loops or charAt methods while returning information using a console, Please leave notes as to compare my program and see where I went wrong or could've used a different method. secondsAfterMidnight Input: String that represents time of day Returns: integer number of seconds after midnight (return -1 if String is not valid time of day) General time of day format HH:MM:SS(AM/PM) These are examples where...

  • 1. Create a MyTime class which is designed to contain objects representing times in 12-hour clock...

    1. Create a MyTime class which is designed to contain objects representing times in 12-hour clock format. Eg: 7:53am, 10:20pm, 12:00am (= midnight), 12:00pm (= noon). You can assume the user will enter times in the format given by the previous examples. Provide a default constructor, a set method which is given a String (eg: “7:53am”), a getHours method, a getMinutes method and a boolean isAm method. Also provide a method for returning a string “morning”, “afternoon”, “evening” or “night”...

  • Modify the hours stage of figure 10-18 to keep military time (00-23 hours) SECTION 10-4/DIGITAL CLOCK...

    Modify the hours stage of figure 10-18 to keep military time (00-23 hours) SECTION 10-4/DIGITAL CLOCK PROJECT 763 AMPM tens hrs PM CLRN 74160 units hrs O] QB QC ENT QD ENP RCO units hrs 2] units-hrs[3] CLRN Tens of hours PRN Units of hours CLRN FIGURE 10-18 Detailed circuitry for the HOURS section to count tens of hours. The BCD counter is a 74160, which has two active- HIGH inputs, ENT and ENP, that are ANDed together internally to...

  • JAVA 1. Create a MyTime class which is designed to contain objects representing times in 12-hour...

    JAVA 1. Create a MyTime class which is designed to contain objects representing times in 12-hour clock like 7:53am, 10:20pm, 12:00am (= midnight), 12:00pm (= noon). Provide a default constructor, a set method which is given a String (eg, “7:53am”), a getHours method, a getMinutes method and a boolean isAm method. Also provide a method for returning a string “morning”, “afternoon”, “evening” or “night” appropriate (in your opinion) to the time. Please see the NOTE below concerning input validation and...

  • POD 3: Tick Tock Instructions There are 24 hours in a day, but we all think...

    POD 3: Tick Tock Instructions There are 24 hours in a day, but we all think about them differently. Some people and places in the world work with a 24-hour clock that goes from 0:00 to 23:59, while others work with a 12-hour clock that goes from 12.00AM to 11:59PM 24-hour clock 0.00 (midnight) 1200 (noon) 23:59 (one minute before midnight), A COLLAPSE 12-hour clock: *12.00 AM" (midnight) *12:00 PM" (noon) "11:59 PM" (one minute before midnight), You are going...

  • For this project you will be writing up a simple Clock program to keep track of...

    For this project you will be writing up a simple Clock program to keep track of time. SimpleClock.java - contains your implementation of the SimpleClock class. You will need to provide the code for a constructor as well as the mutator methods set and tick and the accessor method toString. Look at the comments for each method to see how they should be implemented - the trickiest method is probably tick, which requires that you deal with the changing of...

  • Java Store Time Clock Objects

    1. Create a Time class which is designed to contain objects representing times in 12-hour clock format. Eg: 6:58am, 11:13pm, 12:00am (= midnight), 12:00pm (= noon). You can assume the user will enter times in the format given by the previous examples.Provide a default constructor, a set method which is given a String (eg: “9:42am”), a getHours method, a getMinutes method and a boolean isAm method. Also provide a method for returning a string “morning”, “afternoon”, “evening” or “night” appropriate...

  • What to submit: your answers to exercises 1, and 2 and separate the codes to each...

    What to submit: your answers to exercises 1, and 2 and separate the codes to each question. Create a MyTime class which is designed to contain objects representing times in 12-hour clock format. Eg: 7:53am, 10:20pm, 12:00am (= midnight), 12:00pm (= noon). You can assume the user will enter times in the format given by the previous examples. Provide a default constructor, a set method which is given a String (eg: “7:53am”), a getHours method, a getMinutes method and a...

  • 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...

  • [Java] We have learned the class Clock, which was designed to implement the time of day...

    [Java] We have learned the class Clock, which was designed to implement the time of day in a program. Certain application in addition to hours, minutes, and seconds might require you to store the time zone. Please do the following: Derive the class ExtClock from the class Clock by adding a data member to store the time zone. Add necessary methods and constructors to make the class functional. Also write the definitions of the methods and constructors. Write a test...

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