Need help incrementing the getHour Method - java

I am currently trying to increment my code to add a second and if the second changes the hour and minute, it will be reflected. here is my current code. I know the issue that I am having lies in the get hour method because it is the only one that isn't incrementing. Thank you for the help.
public class Time2
{
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
private int seconds;
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
{
this( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2( int h, int m )
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
// Time2 constructor: hour, minute and second supplied
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
// Time2 constructor: another Time2 object supplied
public Time2( Time2 time )
{
// invoke Time2 three-argument constructor
this( time.getHour(), time.getMinute(), time.getSecond() );
} // end Time2 constructor with a Time2 object argument
// Set Methods
// set a new time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
public void setTime( int h, int m, int s )
{
setHour( h ); // set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
} // end method setTime
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
} // end method setHour
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
} // end method setMinute
// validate and set second
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
} // end method setSecond
// Get Methods
// get hour value
public int getHour()
{
if(minute > 59)
{
hour++;
}
return hour;
} // end method getHour
// get minute value
public int getMinute()
{
if(second > 59)
{
minute++;
}
if(minute > 59)
{
minute = 00;
}
return minute;
} // end method getMinute
// get second value
public int getSecond()
{
if(second > 59)
{
second = 00;
}
return second++;
} // end method getSecond
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
} // end method toString
} // end class Time2
The results that I am getting from my test app are:
public class Time2Test
{
public static void main(String[] args)
{
Time2 t1 = new Time2(); // 00:00:00
Time2 t2 = new Time2(2); // 02:00:00
Time2 t3 = new Time2(21, 34); // 21:34:00
Time2 t4 = new Time2(12, 59, 59); // 12:25:42
Time2 t5 = new Time2(t4); // 12:25:42
System.out.println("Constructed with:");
displayTime("t1: all default arguments", t1);
displayTime("t2: hour specified; default minute and second", t2);
displayTime("t3: hour and minute specified; default second", t3);
displayTime("t4: hour, minute and second specified", t4);
displayTime("t5: Time2 object t4 specified", t5);
// attempt to initialize t6 with invalid values
try
{
Time2 t6 = new Time2(27, 74, 99); // invalid values
}
catch (IllegalArgumentException e)
{
System.out.printf("%nException while initializing t6: %s%n",
e.getMessage());
}
}
// displays a Time2 object in 24-hour and 12-hour formats
private static void displayTime(String header, Time2 t)
{
System.out.printf("%s%n %s%n %s%n",
header, t.toUniversalString(), t.toString());
}
} // end class Time2Test
Output:
Constructed with:
t1: all default arguments
00:00:00
12:00:01 AM
t2: hour specified; default minute and second
02:00:00
2:00:01 AM
t3: hour and minute specified; default second
21:34:00
9:34:01 PM
t4: hour, minute and second specified
12:00:00
12:00:01 PM
t5: Time2 object t4 specified
12:59:59
12:00:00 PM

In this piece of code:
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" )
If minute is greater than 59, the getMinute method will change minute to 0. Then when getHour is called, minute is 0, so hour isn't incremented.
As others have stated, do not modify variables in getters. It causes all kinds of havoc.

Related

(Java begineer) "this" keyword discussion [duplicate]

This question already has answers here:
How do I call one constructor from another in Java?
(22 answers)
Closed 3 years ago.
I know the meaning for "this" keyword.. we use it to reference instance variables if we have a method arguments that has the same name as instance variables but in this code i don't understand why we use it.. what does " this( 0, 0, 0 ) " even mean? we can just put arguments inside the instructors. Can someone please explain?
public class Time2
{
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
{
this ( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2( int h, int m )
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
// Time2 constructor: hour, minute and second supplied
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
// Time2 constructor: another Time2 object supplied
public Time2( Time2 time )
{
// invoke Time2 three-argument constructor
this( time.getHour(), time.getMinute(), time.getSecond() );
} // end Time2 constructor with a Time2 object argument
// Set Methods
// set a new time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
public void setTime( int h, int m, int s )
{
setHour( h ); // set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
} // end method setTime
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
} // end method setHour
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
} // end method setMinute
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
} // end method setSecond
// Get Methods
// get hour value
public int getHour()
{
return hour;
} // end method getHour
// get minute value
public int getMinute()
{
return minute;
} // end method getMinute
// get second value
public int getSecond()
{
return second;
} // end method getSecond
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
} // end method toString
} // end class Time2ere
this( 0, 0, 0 ) call an other constructor with 3 parameters
so
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
calls:
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
with h,m,s = 0
You are simply calling the constructor from within itself.
Let's imagine we have a class Ball:
public class Ball {
private Color color;
private int size;
// This is our constructor
public Ball(Color c, int s) {
this.color = c;
this.size = s;
}
}
Now, if we wanted to create a new red ball with size 4, we could do so with new Ball(Color.RED, 4);
this refers to the current object. So if we are within Ball and creating a new Ball, we would do this(Color.RED, 4);.
This is effectively like saying new Ball();.

how to get near time for the present time [Android Studio]

i have 5 times
example:
4:21 AM
12:1 PM
3:32 PM
6:30 PM
8:4 PM
and the current time is
10:4 AM
I want to do a comparison
What is the next time closest to the current time
the result will be:
NEXT TIME : 12:1 PM
You can turn a time to a date object and then into a long (milliseconds since Jan 1, 1970), and calculate the difference in milliseconds
long diffInMs = currentDate.getTime() - anotherDate.getTime();
And then check which has the smallest difference, but being also equal to or greater than zero. Negative difference means old date and you want the next closest date
To convert the times to dates check this: https://stackoverflow.com/a/8826392/2597775
Basically, it says:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:01:30.500";
Date date = sdf.parse("1970-01-01 " + inputString);
Update: Added logic to rollover at midnight, and added alternative using binary search.
First parse the inputs to a time in milliseconds of the day, by parsing the time string as if it's in UTC time zone.
Then find the smallest value on or after the "current" value, or just smallest value if no value is on or after the "current" value (rollover).
Example:
public static String findNext(String current, String... times) throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("hh:mm a");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
long currentMillis = fmt.parse(current).getTime();
long bestMillis = 0, minMillis = 0;
String bestTime = null, minTime = null;
for (String time : times) {
long millis = fmt.parse(time).getTime();
if (millis >= currentMillis && (bestTime == null || millis < bestMillis)) {
bestMillis = millis;
bestTime = time;
}
if (minTime == null || millis < minMillis) {
minMillis = millis;
minTime = time;
}
}
return (bestTime != null ? bestTime : minTime);
}
Test
System.out.println(findNext("10:4 AM",
"4:21 AM", "12:1 PM", "3:32 PM", "6:30 PM", "8:4 PM"));
System.out.println(findNext("10:4 PM",
"4:21 AM", "12:1 PM", "3:32 PM", "6:30 PM", "8:4 PM"));
Output
12:1 PM
4:21 AM
If the given times are guaranteed to already be sorted, then it can be done with a binary search:
public static String findNext(String current, String... times) {
SimpleDateFormat fmt = new SimpleDateFormat("hh:mm a");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
int idx = Arrays.binarySearch(times, current, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
try {
return fmt.parse(s1).compareTo(fmt.parse(s2));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
if (idx < 0)
idx = -idx - 1;
return times[idx < times.length ? idx : 0];
}
i specially design a function to solve your problem , use function as you needed.
it will works for you surely.
/**
*
* #author Niravdas
*/
public class TimeDiff {
String[] times = { "04:21 AM", "12:01 PM", "03:32 PM", "06:30 PM", "08:04 PM"};
String findingafter="10:04 AM";
public TimeDiff()
{
int time=nextTimeArrayIndex(findingafter,times);
if(time>=0)
System.out.println("NEXT TIME: "+times[time]);
}
public static void main(String argv[])
{
new TimeDiff();
}
int nextTimeArrayIndex(String Finding,String[] fromArray)
{
int shortest=-1,shortestsec=-1;
long minsecdif=(24*60*60+1),minsec=(24*60*60+1);
int hr=Integer.parseInt(Finding.substring(0, 2));
int min=Integer.parseInt(Finding.substring(3, 5));
long seconds = convertToSec(hr, min, 0, Finding.substring(Finding.length()-2));
System.out.println("seconds :" + seconds);
for(int i=0;i<fromArray.length;i++)
{
int temphr=Integer.parseInt(fromArray[i].substring(0, 2));
int tempmin = Integer.parseInt(fromArray[i].substring(3,5));
long tempsec = convertToSec(temphr, tempmin, 0, fromArray[i].substring(Finding.length()-2));
System.out.println("Compared to :" + tempsec);
if((tempsec - seconds) > 0 && minsecdif > (tempsec - seconds))
{
minsecdif = (tempsec - seconds);
shortest = i;
}
if(minsec > tempsec)
{
minsec = tempsec;
shortestsec=i;
}
}
if(shortest >=0)
{
return shortest;
}
else
{
return shortestsec;
}
}
long convertToSec(int hr,int min,int sec,String AMorPM)
{
if(hr==12)
{
hr=0;
}
long secs = (hr*60*60) + (min*60) + (sec*60);
if(AMorPM.equalsIgnoreCase("PM"))
{
secs += (12*60*60);
}
return secs;
}
}
i hope it will solve your problem.

Attempting to add an increment method to a time class

I am attempting to add an increment method for a time class I have. I have modified the original code to only have one private integer "totalseconds" that reads the amount of seconds since midnight. That part of the code works fine but now I am trying to create a method that increments the setSecond, setMinute, and setHour. The problem (I believe) I am having is that these set methods all receive their values from totalseconds not int hour, int minute, int second as before. When I run the test for it the way I have it now I get errors at lines 36, 75 (when attempted to increment seconds via Tick method) and 101 (again only when incrementing seconds via Tick method). I have attached both the Time2 class and Time2Test app for reference.
public class Time2 {
private int totalseconds;
//no argument constructor
public Time2()
{
this(0,0,0); //invoke constructor with three arguments default to 0
}
//constructor with hour supplied minute and second default to 0
public Time2(int hour)
{
this(hour, 0, 0); //invoke constructor with 3 args
}
//constructor with hour and minute supplied seconds default to 0
public Time2(int hour, int minute)
{
this(hour, minute, 0); //invoke constructor with 3 args
}
//Time2 constructor with hour minute and second supplied also tests
public Time2(int hour, int minute, int second)
{
this.totalseconds = (hour * 3600);
this.totalseconds += (minute * 60);
this.totalseconds += (second);
}
public Time2(Time2 time)
{
//invoke constructor with 2 args
this(time.getHour(), time.getMinute(), time.getSecond());
}
// SET and GET methods start here, also Universal time conversion and check
public void setTime(int hour, int minute, int second)
{
if (hour < 0 || hour >= 24)
throw new IllegalArgumentException("Hour must be 0-23");
if (minute < 0 || minute >= 59)
throw new IllegalArgumentException("Minute must be 0-59");
if (second < 0 || second >= 59)
throw new IllegalArgumentException("Hour must be 0-59");
this.totalseconds = (hour * 3600);
this.totalseconds += (minute * 60);
this.totalseconds += second;
}
//validate and set hour
public void setHour(int hour)
{
if (hour < 0 || hour >= 23)
throw new IllegalArgumentException("Hour must be 0-23");
this.totalseconds = (hour * 3600);
}
//validate and set minute
public void setMinute(int minute)
{
if (minute < 0 || minute >= 59)
throw new IllegalArgumentException("Minute must be 0-59");
this.totalseconds += (minute * 60);
}
//validate and set second
public void setSecond(int second)
{
if (second < 0 || second >= 59)
throw new IllegalArgumentException("Second must be 0-59");
this.totalseconds += second;
}
//Get Methods start here
//Get hour
public int getHour()
{
return totalseconds / 3600;
}
//get minute
public int getMinute()
{
return (totalseconds - (3600 * getHour())) / 60;
}
//get second
public int getSecond()
{
return totalseconds - (3600 * getHour())- (60 * getMinute());
}
//Assignment 1-2 tick methods start here.
public void Tick()
{
setSecond(totalseconds ++);
if (totalseconds >= 59) incrementMinute();
}
public void incrementMinute()
{
setMinute( totalseconds ++);
if ( totalseconds >= 59) incrementHour();
}
public void incrementHour()
{
setHour ( this.totalseconds ++);
}
//convert our string to universal format (HH:MM:SS)
public String ToUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}
//conver to standard format (H:MM:SS AM or PM)
public String toString()
{
return String.format("%d:%02d:%02d %s",((getHour() == 0 || getHour() ==
12) ? 12 : getHour() % 12), getMinute(), getSecond(), (getHour()
< 12 ? "AM" : "PM"));
}
}//end class Time2
public class Time2Test
{
public static void main(String[] args)
{
Time2 t1 = new Time2(); //00:00:00
Time2 t2 = new Time2(2); //02:00:00
Time2 t3 = new Time2(21, 34); //21:34:00
Time2 t4 = new Time2(12, 25, 42); //12:25:42
Time2 t5 = new Time2(t4); //12:25:42
System.out.println("Constructed with:");
displayTime("t1: all default arguments", t1);
displayTime("t2: hour specified; defaults for minute and second", t2);
displayTime("t3: hour and minute supplied second defaulted", t3);
displayTime("t4: hour minute and second supplied", t4);
displayTime("t5: Time2 object t4 specified", t5);
//attempt to initialize t6 with invalid args
try
{
Time2 t6 = new Time2(27,74,99); //all invalid values
}
catch (IllegalArgumentException e)
{
System.out.printf("%nException while initializing t6: %s%n",
e.getMessage());
}
System.out.println("Time before increment minute method");
System.out.printf("%s\n", t4.toString());
t4.Tick();
t4.incrementMinute();
t4.incrementHour();
System.out.println("Time after increment minute method");
System.out.printf("%s\n", t4.toString());
}
//display Time2 object in 24 hour and 12 hour formats
private static void displayTime(String header, Time2 t)
{
System.out.printf("%s%n %s%n %s%n", header, t.ToUniversalString(),
t.toString());
}
}

time conversion in JAVA with formula

What I want to do?
I want to return time and display based on user's input. Say, user enters in console starthour: 23 startminute: 45 duration (in min): 30 then the period for start time will be PM offcourse and you can see below I calculated the start time based on the above things, but issue is calculating the endtime. For example, in the above start times, the end time should become 00:15 with the period AM and not PM like start hour.
What I did?
public String toString(){
int h = (getHour()==0 || getHour()==12) ? getHour() : getHour()%12;
String period = (getHour()<12)? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinute(), period);
}
What to do?
The above formula calculates the start time and its period, correctly, but I need a similar formula that can calculate the endhour correctly based on start hour, start minutes and duration entered by the user.
Basically, above mentioned code needs to be manipulated to figure out the endhour, endminute and its period.
Note: Please don't tell about local time use for getting end time and period. Thankyou
EDIT: Here is what I did now:
public String toString(){
int endh = (getEndHour()==0 || getEndHour()==12) ? getEndHour() : getEndHour()%12;
String period = ((getEndHour() + duration) <12)? "AM" : "PM";
return String.format("%02d:%02d %s", endh, getEndHour(), period);
}
you should use 60 modulo for simplicity. here it is
public class Timer {
int hour;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public void addDuration(int duration) {
hour = hour + (minutes + duration)/ 60;
minutes = (minutes + duration) % 60;
}
int minutes;
#Override
public String toString() {
int h = (getHour() == 0 || getHour() == 12) ? getHour()
: getHour() % 24;
String period = (getHour() < 12) ? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinutes(), period);
}
public static void main(String args[]) {
Timer time = new Timer();
time.setHour(23);
time.setMinutes(45);
System.out.println(time.getHour());
time.addDuration(30);
System.out.println(time.getHour());
System.out.println(time);
}
}

Create a toString() method that returns the value as a formatted time String

Im at the last few steps in my homework and need some help understanding/doing the last two steps. The last two things I have to do are:
Create a toString() method that returns the value as a formatted time String. Remember that values less than 10 must be padded with zeroes. For example, midnight will look like this returned from getMilitaryTime(): 00:00:00. Use the String zeroPad(int) method to pad the numbers - see the code below. Use a StringBuffer object to build the String in the toString() method, calling zeroPad(int) as necessary.
Create a main method and construct the following times and print the time using System.out.println(clock):
Call the default constructor (no parameters)
hour: 0, minute: 94, second: 56
hour: 14, minute: 63, second: 64
hour: 98, minute: 76, second: -64
hour: 5, minute: 8, second: 1
hour: 23, minute: 59, second: 59
under just the println at the end I get the error :Syntax error on token "println", = expected after this token. I'm not sure if fixing this will help me move onto the next steps or not. Is what I have for the most part correct when it come to making the toString method?
So Far this is what I have:
//Create a new class called Clock
public class Clock {
public static void main(String[] args){
}
//Create three integer attributes for hour, minute and second.
//Always store the hour in military time.
private double MilitaryHour;
private double Minute;
private double Second;
// Create setters for the hour, minute and second values.
public double getMilitaryHour() {
return MilitaryHour;
}
public void setMilitaryHour(double militaryHour) {
if(militaryHour < 0 || militaryHour > 23)
this.MilitaryHour = (militaryHour % 24);
this.MilitaryHour = militaryHour;
}
public double getMinute() {
return Minute;
}
public void setMinute(double minute) {
if(minute < 0 || minute > 59)
this.Minute = (minute % 60);
this.Minute = minute;
}
public double getSecond() {
return Second;
}
public void setSecond(double second) {
if(second < 0 || second > 59)
this.Second = (second % 60);
this.Second = second;
}
public Clock(double MilitaryHour,double Minute,double Second) {
this.MilitaryHour = MilitaryHour;
this.Minute = Minute;
this.Second = Second;
}
/default
public Clock(){
this(0.0, 0.0, 0.0);
}
public String toString()
{
String result = "Hour: " + getMilitaryHour()+"Minute: " + getMinute()+ "Seconds:" + getSecond();
return result;
}
System.out.println("" + result.toString());
}
A quick look shows me that your implementation contains many errors.
Your statement System.out.println("" + result.toString()); is not placed correctly. It should be place inside a function, may be inside your main function.
The result.toString() doesn't make sense. With what I understood from your problem, you need to create a Clock object like this:
Clock clock = new Clock(1, 1, 1);
Then,
System.out.println(clock.toString());
To print the object. Like this:
public static void main(String[] args){
Clock clock = new Clock(1, 1, 1);
System.out.println(clock.toString());
}
I am not sure if this would be enough, but this should fix some of your issues.

Categories

Resources