I was asked to only used the updateDisplay() method to change the format for the hour in this clockDisplay, eveythings works perfectly the hour can get to 12:59PM and use the method timeTick() it gets to 1:00PM but after using timeTick() again it goes to 1:01AM again. How can i fix this problem?
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString;
public ClockDisplay()
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
updateDisplay();
}
public ClockDisplay(int hour, int minute)
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
setTime(hour, minute);
}
public void timeTick()
{
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
updateDisplay();
}
public void setTime(int hour, int minute)
{
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
}
public String getTime()
{
return displayString;
}
private void updateDisplay()
{
int h = hours.getValue()%12;
String format = (hours.getValue()/12 == 0 ? "AM":"PM");
if(h == 0)
{
h = 12;
}
else if(hours.getValue() > 12)
{
hours.setValue(hours.getValue() - 12);
}
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue() + format;
}
}
What’s wrong? When the time reaches 1 PM, your updateDisplay method sets the value of the hours display back to 1. Now your clock display object is back in the state it had at 1 AM, that is, you have no way of distinguishing those two times.
How to fix? I suggest you introduce an instance variable (field) to hold the information whether we are in the AM or PM period of the day. You may use a Boolean variable or introduce an enum with two constants like AM and PM. Then you need to set this variable in the timeTick method and also in your setTime method. Then it will be fairly straightforward to use this variable to decide whether to display the string AM or PM in your updateDisplay method.
If you are asked to do this without adding a new field: then you need to let the hours in the hours display run to 23 so you keep track of whether you are in the AM or PM time of day. So in updateDisplay don’t set the hours value. Only in the display string generated put 12 instead of 0 and 1 through 11 instead of 13 through 23.
For production code: In real life one wouldn’t use a design like yours and would rely heavily on standard library classes for handling time. One would have a clearer separation between model (the current time) and presentation (the string printed). So the current time would be held in a LocalTime:
private LocalTime time;
Ticking the time 1 minut forward:
time = time.plusMinutes(1);
For displaying the time you would use a DateTimeFormatter:
private static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
With this the display string is created this way:
displayString = time.format(TIME_FORMATTER);
The code is not tested, so forgive if there is a typo.
Related
i have one function
callEach24hourOneTime();
i have to call this function in each 24 hour only one time within 24 once it will executed then i don't have to call callEach24hourOneTime
i am unable to get current time hour minute and second in millis so that i can apply condition i tried below logic but unable to execute.
if(currentmillis=86400000 ){
callEach24hourOneTime();
}
else {
//dont call do other operation
}
please suggest me solution for this .
Logic to always have at least 24 hours between executions of the callEach24hourOneTime() method:
private long nextCallMillis;
long currentMillis = System.currentTimeMillis();
if (currentMillis >= this.nextCallMillis) {
this.nextCallMillis = currentMillis + 86400000/*24 hours*/;
callEach24hourOneTime();
} else {
// ...
}
That will cause a drift in time-of-day for the execution of the method. The speed of the drift is determined by how often the code is execute.
If you instead want method to be called at (around) the same time every day:
private long nextCallMillis;
long currentMillis = System.currentTimeMillis();
if (this.nextCallMillis == 0)
this.nextCallMillis = currentMillis; // Establish time-of-day
if (currentMillis >= this.nextCallMillis) {
this.nextCallMillis += ((currentMillis - this.nextCallMillis) / 86400000 + 1) * 86400000;
callEach24hourOneTime();
} else {
// ...
}
"Same time every day" is in UTC, so when crossing Daylight Savings Time changes, the time-of-day will change by 1 hour.
UPDATE
If you just want "once per day" logic:
private LocalDate lastCallDate;
LocalDate today = LocalDate.now();
if (! today.equals(lastCallDate)) {
this.lastCallDate = today;
callOnceDailyOneTime();
} else {
// ...
}
You can you a cron library.
I don't really know what language or framework you are currently using, but from spring I'd say you can use #Scheduled :
#Scheduled(cron = "0 0 0 * * *")
private void myMethod(){}
For exemple the cron above will make myMethod() execute once a day.
Hey guys so i need help with my setTime method. Basically this is the question in my assignment:
Consider a class Time that represents a time of day. It has attributes for the
hour and minute. The hour value ranges from 0 to 23, where the range 0 to
11 represents a time before noon. The minute value ranges from 0 to 59.
a. Write a default constructor that initializes the time to 0 hours, 0 minutes.
b. Write a private method isValid(hour, minute) that returns true if the
given hour and minute values are in the appropriate range.
c. Write a method setTime(hour, minute) that sets the time if the given
values are valid.
I need help with c, in my code you can see that i have the set time method but when i run my programs and enter the time it returns this instead of the numbers in entered:
Please enter the hour
3
Please enter the minute
23
The time is time.Time#4d546e25 time.Time#620b66cc
BUILD SUCCESSFUL (total time: 3 seconds)
My code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package time;
/**
*
* #author 797286001
*/
public class Time {
/**
* #param args the command line arguments
*/
//default constructor
public static int hour;
public static int minute;
public Time(){
hour = 0;
minute = 0;
}
private static boolean isValid(int hour, int minute)
//returns true if given hour & minute values are in range
{
if((hour >= 0 && hour <= 23) && (minute >= 0 && minute <=11))
{
return true;
}
else
{
return false;
}
}
public void setTime(int hour, int minute)
//set time if given values are valid -
{
}
public static void main(String[] args) {
//
Time.hour = 0;
Time.hour = 0;
Time hour = new Time();
Time minute = new Time();
System.out.println("The time is " + hour + " " + minute);
}
}
setTime should not be reading anything from the keyboard; the parameters contain the values you need.
Time hour = new Time();
Time minute = new Time();
This creates two instances of your class named hour and minute. Then you try to print them out. The default toString() method prints out their location in memory.
Go ahead and create one instance of the class, then use that to call the methods you need to call. Also, your setTime method takes 2 parameters but doesn't use them.
OK, so i'm new to this and have just signed up however i need some help with explanations please..
I have a assignment which has asked me to convert a 24 hour clock into a 12 hour clock by making some adjustments. I am pretty sure I am almost there however I cannot get the boolean to switch when the hour changes using the timeTick method in the code. To be honest I believe the rest is fine but any help would be appreciated:
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString;
private boolean isAM;
/**
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at 00:00.
*/
public ClockDisplay()
{
hours = new NumberDisplay(12);
minutes = new NumberDisplay(60);
updateDisplay();
setMorn();
}
/**
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at the time specified by the
* parameters.
*/
public ClockDisplay(int hour, int minute)
{
hours = new NumberDisplay(12);
minutes = new NumberDisplay(60);
setTime(hour, minute);
setMorn();
}
/**
* This method should get called once every minute - it makes
* the clock display go one minute forward.
*/
public void timeTick()
{
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
if (hours.getValue() == 12)
{
isAM = !isAM;
}
updateDisplay();
}
private void setMorn()
{
isAM = true;
}
private void setAft()
{
isAM = false;
}
/**
* Set the time of the display to the specified hour and
* minute.
*/
public void setTime(int hour, int minute)
{
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
}
/**
* Return the current time of this display in the format HH:MM.
*/
public String getTime()
{
return displayString;
}
/**
* Update the internal string that represents the display.
*/
private void updateDisplay()
{
int hour = hours.getValue();
String daynight;
if (isAM = true)
{
daynight = "AM";
if (hour == 0)
{
hour = 12;
}
}
else
{
isAM = false;
daynight = "PM";
if (hour == 0)
{
hour = 12;
}
}
displayString = hour + ":" +
minutes.getDisplayValue() + daynight;
}
}
What We have
Add a boolean field isAM which will have the value true (it is morning) and false (it is afternoon).
We create two new methods; setMorning which sets isAM to be true and setAfternoon which sets isAM to be false.
Both constructors will initialise the time of day to be morning by default and so both invoke setMorning.
In timeTick we need to check whether the hours rolled over, meaning it either changed from am to pm or from pm to am. Note the use of: isAM = !isAM
In updateDisplay we need to create the suffix "am" or "pm" depending on whether isAM is true or false.
Your problem is almost certainly in the line that reads:
if (isAM = true)
This is actually setting isAM to true and the result of the expression is therefore also true so the else part will never be executed.
You probably meant:
if (isAM == true)
or - better still:
if (isAM)
OK, so i finally worked it out thanks to Dragondraikk who made me think. The issue was just as he suggested, well kind of. as I set the hours to 0 - 11 and tick over. I was not changing 0 into a 12 until the updateDisplay was run so it was actually a 0 and not a twelve:
public void timeTick()
{
minutes.increment()
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
if (hours.getValue() == 0)
{
isAM = !isAM;
}
updateDisplay();
}
This fixed the problem and now it works :) thank you everyone for all your help.I am also aware that I can provide feedback in the form of a rating, if someone can tell me how I am more than happy to do so :)
Below is my code.
public class TestCalendar {
public static void main(String[] args){
int unique_id = Integer.parseInt("" + Calendar.HOUR + Calendar.MINUTE
+ Calendar.SECOND);
System.out.println(unique_id);
}
}
Calendar.HOUR is supposed to give me
public static final int HOUR Field number for get and set indicating the hour of the morning or
afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not
by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
It doesnt matter how many times I run this code, it always gives me the same unique_id. (101213) and my local time on my machine is 1:30pm. What am I doing wrong here?
Thanks.
Your code is just concatenating constants, that the Calendar defines to identify some of it's fields. To get values of these fields, call Calendar.get() and pass the constant identifier as an argument:
public class TestCalendar {
public static void main(String[] args){
Calendar c = Calendar.getInstance();
int unique_id = Integer.parseInt("" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE)
+ c.get(Calendar.SECOND));
System.out.println(unique_id);
}
}
The above would work, but the result will be far from unique ID.
To get an ID uniquely identifying a point in time (with the precision of milliseconds), consider Calendar.getTimeInMillis().
Calendar.HOUR, Calendar.MINUTE and Calendar.SECOND are public static int field of the Calendar class. Their value is
CALENDAR.HOUR: 10
CALENDAR.MINUTE: 12 and
CALENDAR.SECOND: 13.
Your String concatenation is just appending this values. To read from a Calendar you could so something similar to
calendar.get(Calendar.HOUR);
calendar.get(Calendar.MINUTE);
I am not sure what is requirement but if you want system time then may be you can use this "System.currentTimeMillis()"
Calendar.HOUR (or MINUTE, SECOND) is just an indicator that indicates which field we want to extract from the Calendar instance, not the value, i.e. we want to 'extract HOUR from the calendar object' like below:
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY); // in 24-hours,
// or c.get(Calendar.HOUR) in 12-hours.
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int weekday = c.get(Calendar.DAY_OF_WEEK);
int weekOfYear = c.get(Calendar.WEEK_OF_YEAR);
For those who are still having some problems with this, like I did, especially when you want to print multiple times you may need to to use new like follows:
System.out.println(""+new GregorianCalendar().get(Calendar.HOUR_OF_DAY)+":"+new GregorianCalendar().get(Calendar.MINUTE)+":"+new GregorianCalendar().get(Calendar.SECOND)+":"+new GregorianCalendar().get(Calendar.MILLISECOND));
Add two more constructors that are analogous to the set Time methods described in parts c and d.
Part c: Write a method setTime(hour, minute) that sets time if the given values are valid.
public void SetTime(int newHour, int newMinute)
{
if (hourIsValid = true)
hour = newHour;
if (minuteIsValid = true)
minute = newMinute;
}
Part d: Write another method setTime(hour,minute,isAm) that sets the time if the given values are valid. The given hour should be in the range of 1 to 12. The parameter isAM is true if the time is an a.m time and false otherwise.
public void SetTime(int newHour, int newMinute, boolean isAM)
{
if (hour >=0 && hour < 12)
{ isAM = true;
hour = newHour;}
if (minuteIsValid = true)
minute = newMinute;
if (isAM = true)
System.out.println ( hour + "a.m");
else
nightHour = hour % 12;
System.out.println( nightHour + "p.m");
}
That is what i produced so far, what is being asked to be produced by analogous? I know it means similar but w does it mean like for part C just the two separate like SetHour and SetMinute?
Every class can have multiple constructors, each one can get different variables.
For this homework, you should add constructors that get the values similar to the setters functions, and use the setters:
public ClassName(int newHour, int newMinute)
{
SeTime(newHour, newMinute);
}
The question simply means write two constructors for the class in question (you haven't mentioned the name of it) that perform the same function as the methods described in part (c) and (d); i.e. they initialise the class with the hour and minute, and with the hour, minute and "am" flag respectively.
For example:
Method: public void setTime(int hour, int minute)
Analagous constructor: public Time(int hour, int minute)
Note that the constructor can simply chain to the method call; e.g.
public Time(int hour, int minute) {
setTime(hour, minute);
}
However, typically a constructor may be used to initialise final fields and hence will not chain to a setter; e.g.
public Time(int hour, int minute) {
this.hour = hour;
this.minute = minute;
}