I am really new to programming. I am doing an assignment for my intro to Java. In my assignment, we need to find the total number of seconds since midnight and changed this number to hours, minutes and seconds to show the current time. I have small problem. when I test my code, the totalseconds show 0! any help would be appreciated. Sorry the code is a chaos
package clock;
import java.text.DecimalFormat;
import java.util.Calendar; // to get current time
public class Clock {
public static int totalseconds;
public static int seconds;
public static int minutes;
public static int hours;
public static int test;
public Clock(int hours, int minutes, int seconds ) {
setHours(hours);
setMinutes(minutes);
setSeconds(seconds);
}
// use current time
public Clock() {
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;
totalseconds = (int) secondsPassed;
}
public void tick() {
addSecond();
}
private void addSecond() {
seconds = totalseconds%60;
}
private void addMinute() {
minutes = totalseconds/60 % 60;
}
private void addHour() {
hours = totalseconds / 3600;
}
public String toString() {
DecimalFormat f = new DecimalFormat("00");
return f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
// the total number of minutes sinces midnight
public int getTotalMinutes() {
return totalseconds / 60 % 60;
}
// the total number of seconds since midnight
public int getTotalSeconds() {
return totalseconds;
}
public void setHours(int hours) {
if (hours > 23 || hours < 0) {
this.hours = 0;
}
else
this.hours = hours;
}
public void setMinutes(int minutes) {
if (minutes > 59 || minutes < 0)
this.minutes = 0;
else
this.minutes = minutes;
}
public void setSeconds(int seconds) {
if (seconds > 59 || seconds < 0)
this.seconds = 0;
else
this.seconds = seconds;
}
// reset hours, minutes and seconds to zero
public void reset() {
hours = minutes = seconds = 0;
}
public static void main(String [] args){
System.out.println("this is total seconds " + test + totalseconds );
}
}
Change main to this.
public static void main(String [] args){
Clock clock = new Clock();
System.out.println("this is total seconds " + test + totalseconds );
}
New you make an instance of Clock and the constructor is called, where all your magic happens.
I agree with what #shmosel suggested. There seems to be confusion in how to use instance variable. Further, I think you should take advantages of Java 8 methods for your time part.
class Clock {
private int totalseconds;
private int seconds;
private int minutes;
private int hours;
int test;
public Clock(int hours, int minutes, int seconds) {
setHours(hours);
setMinutes(minutes);
setSeconds(seconds);
}
// use current time
public Clock() {
LocalTime now = LocalTime.now(ZoneId.systemDefault());
totalseconds = now.toSecondOfDay();
}
public void tick() {
addSecond();
}
private void addSecond() {
seconds = totalseconds % 60;
}
private void addMinute() {
minutes = totalseconds / 60 % 60;
}
private void addHour() {
hours = totalseconds / 3600;
}
public String toString() {
DecimalFormat f = new DecimalFormat("00");
return f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
// the total number of minutes since midnight
public int getTotalMinutes() {
return totalseconds / 60 % 60;
}
// the total number of seconds since midnight
public int getTotalSeconds() {
return totalseconds;
}
public void setHours(int hours) {
if (hours > 23 || hours < 0) {
this.hours = 0;
} else
this.hours = hours;
}
public void setMinutes(int minutes) {
if (minutes > 59 || minutes < 0)
this.minutes = 0;
else
this.minutes = minutes;
}
public void setSeconds(int seconds) {
if (seconds > 59 || seconds < 0)
this.seconds = 0;
else
this.seconds = seconds;
}
// reset hours, minutes and seconds to zero
public void reset() {
hours = minutes = seconds = 0;
}
}
public class SecondsSinceMidnight {
public static void main(String[] args) {
Clock myClock = new Clock();
System.out.println("Total seconds that elapsed since midnight:" + myClock.getTotalSeconds());
System.out.println("Converted to Minutes: " + myClock.getTotalMinutes());
}
}
Related
I am trying to make a clock program using Java, and I got everything to work properly except I cannot get the program to change the negative values to 0. I also cannot get the program to set the values of hours, minutes, and seconds to 0 if they are out of range. I have a tester program that I have to use and the T1 and T2 clock values are incorrect in my code. T1 should be 0:0:0 and T2 should be 0:0:0 as well. However, when I output my code it comes out as T1 being -3:-21:-30 and T2 is 24:60:60. I know there is something wrong with my code, but I can't find the issue, if anyone would be able to help me that would be greatly appreciated. Below is my code and then the second section is the tester code that I have to use.
public class Clock
{
// instance variables
private int hours;
private int minutes;
private int seconds;
public void setHours(int newHours) {
hours = newHours;
if (hours<0 || hours > 24) {
hours = 0;
}
}
public void setMinutes(int newMinutes) {
minutes = newMinutes;
if (minutes<0 || minutes > 60) {
minutes = 0;
}
}
public void setSeconds(int newSeconds) {
seconds = newSeconds;
if(seconds<0 || seconds > 60) {
seconds = 0;
}
}
/**
* Constructor for objects of class Clock
*/
public Clock(int newHour, int newMinute, int newSecond)
{
if (newHour > -1 || newHour < 24) {
this.hours = newHour;
}
else {
setHours(hours);
}
if (newMinute > -1 || newMinute < 60) {
this.minutes = newMinute;
}
else {
setMinutes(minutes);
}
if (newSecond > -1 || newSecond < 60) {
this.seconds = newSecond;
}
else {
setSeconds(seconds);
}
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public String toString() {
return hours + ":"+minutes+":"+seconds;
}
public void tick() {
seconds = seconds +1;
if(seconds >= 60)
{
minutes ++;
seconds = 0;
}
if(minutes >= 60)
{
hours++;
minutes = 0;
}
if(hours >=24)
{
hours = 0;
}
}
}
The next piece is the tester code.
public class ClockTest {
public static void main(String [] args){
//Create some clocks and print their times
Clock c1 = new Clock(-3,-21,-30);
System.out.println("T1: "+ c1);
c1 = new Clock(24,60,60);
System.out.println("T2: "+ c1);
c1 = new Clock(3,21,30);
System.out.println("T3: "+ c1);
//Tick the clock twice and print its time
c1.tick();
c1.tick();
System.out.println("T4: "+ c1);
c1 = new Clock(3,30,59);
c1.tick();
System.out.println("T5: "+ c1);
c1 = new Clock(3,59,59);
c1.tick();
System.out.println("T6: "+ c1);
c1 = new Clock(23,59,59);
c1.tick();
System.out.println("T7: "+ c1);
c1 = new Clock(0,0,1);
c1.tick();
System.out.println("T8: "+ c1);
c1 = new Clock(1,1,1);
c1.setHours(22);
c1.setMinutes(30);
c1.setSeconds(35);
System.out.println("T9: "+ c1);
System.out.println("T10: " + c1.getHours() + ":"
+c1.getMinutes() + ":" + c1.getSeconds());
}
}
Your condition is wrong.
When you write this:
if (newHour > -1 || newHour < 24) {
You really mean this:
if (newHour > -1 && newHour < 24) {
#nicomp is correct and you should also be using >= 24 and 60 instead of >. You might consider changing the constructor for Clock to
public Clock(int newHour, int newMinute, int newSecond) {
setHours(newHour);
setMinutes(newMinute);
setSeconds(newSecond);
}
and then do all of your validation in the set methods, instead of having some validation in the set methods and some in the constructor.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Rate_Per_Hour {
public static void main(String[] args) {
String TimeStart = "09.30.00 am";
String TimeEnd= "10.10.00 am";
SimpleDateFormat format = new SimpleDateFormat("hh.mm.ss a");
int total=0;
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(TimeStart);
d2 = format.parse(TimeEnd);
long diff = d2.getTime() - d1.getTime();
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffMinutes = diff / (60 * 1000) % 60;
if (diffMinutes <= 30) {
total = 20;
}
else if (diffHours <=1){
total = 35;
}
System.out.println("Rs." +total);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want output like this:
(Fixed rate per hour for this is Rs.35 )
For 30 min = Rs.20
For 40 min = Rs.25 and so on......
For 1 hour = Rs.35
For 1 hour 10 min = Rs.40
Please help me, figure out how I can do this.
Since the rate increases by 5 every 10 minutes, so just use a simple function to return the rate:
public double rate(int minutes)
{
return 20 + 5*((minutes - 30)/10);
}
Calculate the number of minutes and then pass it as an argument in that function to get the rate. Also, try to keep your code as short as possible but at the same time, simple.
if you need something more flexible rather than fixed rate you could implement an enum with predefined stops
you could define any rate you want for a given time.
for example if long running tasks shall gain higher rates (from your question it was not obvious to me if this rate shall be just the calculated value as in Manish Kundu's answer or if other values might get assigned.)
with this code you could assign higher rates for long running jobs (for example in computer games, jobs that are harder to achieve you return a higher rate or you lower the rate because the player took too much time...)
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class TimeMain {
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh.mm.ss[ ]a");
public enum Rate {
STOP0(0, 0, 0), // default
STOP1(0, 30, 20), // 30 mins -> Rs.20
STOP2(0, 40, 25), // 40 mins -> Rs.25
STOP3(1, 0, 35), // 1 hour -> Rs.35
STOP4(1, 10, 40); // 1 hour 10 minutes -> Rs.40
int minutes = 0;
int rate = 0;
/*
* hours is actually not needed as 1h10 = 70mins...
*/
private Rate(int hours, int minutes, int rate) {
this.minutes = minutes + hours * 60;
this.rate = rate;
}
public static Rate from(String timeStart, String timeEnd) {
LocalTime time1 = LocalTime.parse(timeStart.toUpperCase(), dateTimeFormatter);
LocalTime time2 = LocalTime.parse(timeEnd.toUpperCase(), dateTimeFormatter);
long minutesBetween = ChronoUnit.MINUTES.between(time1, time2);
for (int i = 0; i < Rate.values().length; i++) {
Rate r = Rate.values()[i];
if (r.minutes > minutesBetween) {
return Rate.values()[i-1];
}
}
return STOP0;
}
public String toString() {
return String.format("Rs.%s", rate);
}
}
public static void main(String... args) {
String timeStart = "09.30.00 am";
String timeEnd = "10.10.00 am";
System.out.println(Rate.from(timeStart, timeEnd));
}
}
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());
}
}
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);
}
}
I want to represent time with my time class. I can't use get and set methods.Only I can use listed methods on the code.But it doesn't work.
It returns 0:0:0.
public int addHours(int hours)
{
if(hours>=0&&hours<=23)
{
return hours;
}
return 0;
}
public int addMinutes(int minutes)
{
if(minutes>=0&&minutes<=59)
{
return minutes;
}
return 0;
}
public int addSeconds(int seconds)
{
if(seconds>=0&&seconds<=59)
{
return seconds;
}
return 0;
}
public String showTime()
{
return hours+":"+minutes+":"+seconds;
}
}
your code does nothing.
you need to do something like this:
public void addHours( int hours ){
this.hours += hours; // add hours
this.hours %= 24; // roll over at 24 hours
}
public void addMinutes( int minutes ){
this.minutes += minutes; // add minutes
addHours(this.minutes/60); // carry over to hours
this.minutes %= 60; // roll over at 60 minutes
}
public void addSeconds( int seconds ){
this.seconds += seconds; // add seconds
addMinutes(seconds/60); // carry over to minutes
this.seconds %= 60; // roll over at 60 seconds
}
(it probably won't matter, but this is not thread safe at all)
but this is generally a bad idea. Java 8 has a beautiful time api, pre Java-8 there is the JodaTime library (which is actually the basis of the Java 8 time api). It seems what you want to do could benefit from LocalTime:
LocalTime t = LocalTime.of(13,50,27).addHours(1).addMinutes(1).addSeconds(1);
System.out.println(t.toString());
// prints 14:51:28
Use java.util.Calendar and java.text.SimpleDateFormat:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.add(Calendar.HOUR, 5);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));