Checking if a method is set - java

"a fourth field to keep track of whether or not the alarm is set; alternatively, you could set the alarm fields to a negative value (-1 is my favorite)." Please help, I am trying to create a field which checks if my method is set. I've tried an if and statement so far but it probably is not the way to go. I need to check that my alarm is set. Probably going to need a return value then right?
public void setAlarm (int hours, int minutes, int seconds)
{
if(hours minutes seconds > 0) {
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
}
else {
System.out.println("Please set the alarm.");
}
}

I believe this is what is intended.
private boolean isSet;
public boolean isAlarmSet()
{
return isSet;
}
public void setAlarm (int hours, int minutes, int seconds)
{
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
isSet = true;
}

Related

Having trouble developing incrementMinutesBy method

I am trying to create a digital clock an am currently trying to fix my incrementMinutesBy method. 
I need this method to increase both the minutes and if necessary the hours. I need the final this.minutes to be the sum of the previous this.minutes and the parameter, modulo the number of minutes in an hour.
I also need the final this.hours to be the sum of the previous this.minutes and the parameter, divided by the number of minutes in an hour. My method so far begins on line 94.
public class DigitalClock
{
private int currentHour;
private int currentMinutes;
public int getHour()
{
return currentHour;
}
public void setHour(int currentHour)
{
this.currentHour = currentHour;
}
public int getMinutes()
{
return currentMinutes;
}
public void setMinutes(int currentMinutes)
{
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given
* hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock (int hour, int minutes) // 2-parameter constructor (parameters: int hour and int minutes)
{
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX){
currentHour = hour;
}
else {
currentHour = 0;
//throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
//throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours.
* If the hours advances past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward
* by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour)
{
int h = getHour()+hour; {
// if statement enforcing precondition
if(h>HOUR_MAX)
h%=TOTAL_NUMBERS_HOURS;
// increasing this.hours by the parameter
setHour(h);}
// if statement which prevents negative hours from being inputted
if (h<HOUR_MIN) {
throw new IllegalArgumentException("Invalid input. No negative hours");
}
}
public void incrementMinutesBy(int minutes) {
int m = getMinutes()+minutes;
m++;
if (m > MINUTES_MAX) {
m%=TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
if (m<MINUTES_MIN) {
throw new IllegalArgumentException("Invalid input. No negative minutes");
}
else
{
System.out.println("Minutes are: "+m);
}
}
public static void main(String args[])
{
DigitalClock obj=new DigitalClock(12, 15);
obj.incrementHoursBy(HOUR_MAX);
obj.incrementMinutesBy(MINUTES_MAX);
DigitalClockFormatter();
}
public static void DigitalClockFormatter() {
// method for class DigitalClockFormatter
}
}
To simplify the implementation, it's beter to save totalMinutes internaly, but not the separate hours and minutes.
public final class DigitalClock {
private static final int MINUTES_PER_HOUR = (int)TimeUnit.HOURS.toMinutes(1);
private static final int MINUTES_PER_DAY = (int)TimeUnit.DAYS.toMinutes(1);
private int totalMinutes;
public DigitalClock(int hour, int minutes) {
setHour(hour);
setMinutes(minutes);
}
public int getHour() {
return totalMinutes / MINUTES_PER_HOUR;
}
public int getMinutes() {
return totalMinutes % MINUTES_PER_HOUR;
}
public void setHour(int hour) {
if (hour < 0 || hour > 23)
throw new IllegalArgumentException("'hour' should be within [0;23]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(hour) + getMinutes();
}
public void setMinutes(int minutes) {
if (minutes < 0 || minutes > 59)
throw new IllegalArgumentException("'minutes' should be within [0;59]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(getHour()) + minutes;
}
public void incrementHoursBy(int hour) {
totalMinutes = withinDay((int)TimeUnit.HOURS.toMinutes(hour) + totalMinutes);
}
public void incrementMinutesBy(int minutes) {
totalMinutes = withinDay(totalMinutes + minutes);
}
private static int withinDay(int totalMinutes) {
totalMinutes %= MINUTES_PER_DAY;
if (totalMinutes < 0)
totalMinutes = MINUTES_PER_DAY + totalMinutes;
return totalMinutes;
}
#Override
public String toString() {
return String.format("%02d:%02d", getHour(), getMinutes());
}
}
I believe that your calculations can also be achieved by subtraction. Consider the following example.
If currentHour is 23 and you add two hours, then the result should be 1 (one).
23 + 2 = 25
25 % 24 = 1
25 - 24 = 1
Similarly for currentMinutes. However, for currentMinutes you also need to increment currentHour if the result of the increment (to currentMinutes) is greater than MINUTES_MAX. And when you increment currentHour you also need to check whether the incremented currentHour value is greater than HOUR_MAX. In other words, if currentHour is 23 and currentMinutes is 55 and you incrementMinutesBy(10), then:
55 + 10 = 65
65 - 60 = 5
Therefore currentMinutes is set to 5 and currentHour needs to be incremented. Therefore:
23 + 1 = 24
24 - 24 = 0
So currentHour needs to be set to 0 (zero).
Also, as explained in the book Java by Comparison, methods need to fail fast so the first thing you should do in both method incrementHoursBy and method incrementMInutesBy is to check the value of the method argument – and not the result of the calculation. After all, you wrote in the code comments that the pre-condition is that the method argument not be negative – even though I think it would be logical to be able to set the digital clock backwards. I mean that's what you do when daylight saving ends and the clocks get turned back one hour. But then again, with your [digital] clock, you could achieve the same result by invoking incrementHoursBy(HOUR_MAX)
Consider the following code:
public class DigitalClock {
private int currentHour;
private int currentMinutes;
public int getHour() {
return currentHour;
}
public void setHour(int currentHour) {
this.currentHour = currentHour;
}
public int getMinutes() {
return currentMinutes;
}
public void setMinutes(int currentMinutes) {
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock(int hour, int minutes) {
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX) {
currentHour = hour;
}
else {
currentHour = 0;
// throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
// throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours. If the hours advances
* past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour) {
// if statement which prevents negative hours from being inputted
if (hour < HOUR_MIN || hour > HOUR_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 23");
}
int h = currentHour + hour;
// if statement enforcing precondition
if (h > HOUR_MAX) {
h -= TOTAL_NUMBERS_HOURS;
}
// increasing this.hours by the parameter
setHour(h);
}
public void incrementMinutesBy(int minutes) {
if (minutes < MINUTES_MIN || minutes > MINUTES_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 59");
}
int m = getMinutes() + minutes;
if (m > MINUTES_MAX) {
incrementHoursBy(1);
m -= TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
}
public static void main(String args[]) {
DigitalClock obj = new DigitalClock(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
DigitalClockFormatter(obj);
}
public static void DigitalClockFormatter(DigitalClock dc) {
System.out.printf("%02d:%02d", dc.getHour(), dc.getMinutes());
}
}
Running above code displays:
00:05
Alternatively, you could use the date-time API.
import java.time.LocalTime;
public class DigiClok {
private LocalTime clock;
public DigiClok(int hour, int minute) {
clock = LocalTime.of(hour, minute); // throws java.time.DateTimeException if invalid arguments
}
public int getHour() {
return clock.getHour();
}
public void setHour(int currentHour) {
// class 'java.time.LocalTime' is immutable.
int minute = clock.getMinute();
clock = LocalTime.of(currentHour, minute);
}
public int getMinutes() {
return clock.getMinute();
}
public void setMinutes(int currentMinutes) {
int hour = clock.getHour();
clock = LocalTime.of(hour, currentMinutes);
}
public boolean equals(Object obj) {
boolean equal = this == obj;
if (!equal) {
if (obj instanceof DigiClok) {
DigiClok other = (DigiClok) obj;
equal = clock.equals(other.clock);
}
}
return equal;
}
public int hashCode() {
return clock.hashCode();
}
public String toString() {
return clock.toString();
}
public void incrementHoursBy(int hour) {
clock = clock.plusHours(hour); // also handles negative 'hour'
}
public void incrementMinutesBy(int minutes) {
clock = clock.plusMinutes(minutes); // also handles negative 'minute'
}
public static void main(String[] args) {
DigiClok obj = new DigiClok(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
System.out.println(obj);
}
}

How to validate certain element of object created inside the LinkedList

My current task is to create Linked List with Clock objects in it. Furthermore, I have to create a method that will add one minute to each clock inside the Linked List.
There is one thing I thought about and I would like to add to this task as my idea - i called it validator. I want it to validate if there is 60 minutes on the clock, so it will change hour and minutes after adding this one minute.
I tried to create diffrent methods and if variations. I ran out of any ideas.
import java.util.*;
import java.io.*;
import java.lang.*;
import java.time.*;
class Clock {
private int hours;
private int minutes;
public Clock (int hours, int minutes){
this.hours = hours;
this.minutes = minutes;
}
public int getHours() {
return hours;
}
public int getMinutes(){
return minutes;
}
public int addOneMinute(){
return minutes = minutes + 1;
}
public int hoursSwapper(){
return (hours = hours + 1);
}
public int minutesSwapper() {
return (minutes = 00);
}
public String toString() {
return "Clock time is " + hours + "." + minutes;
}
}
class Program{
public static void main (String [] args) throws java.lang.Exception{
Random hoursGenerator = new Random();
Random minutesGenerator = new Random();
Clock clock0 = new Clock(hoursGenerator.nextInt(24), minutesGenerator.nextInt(60));
Clock clock1 = new Clock(hoursGenerator.nextInt(24), minutesGenerator.nextInt(60));
Clock clock2 = new Clock(hoursGenerator.nextInt(24), minutesGenerator.nextInt(60));
Clock clock3 = new Clock(hoursGenerator.nextInt(24), minutesGenerator.nextInt(60));
Clock clock4 = new Clock(hoursGenerator.nextInt(24), minutesGenerator.nextInt(60));
LinkedList<Clock> clockCollection = new LinkedList<Clock>();
clockCollection.add(clock0);
clockCollection.add(clock1);
clockCollection.add(clock2);
clockCollection.add(clock3);
clockCollection.add(clock4);
for (int j = 0; j < clockCollection.size(); j ++){
System.out.println(clockCollection.get(j));
clockCollection.get(j).addOneMinute();
System.out.println(clockCollection.get(j));
if (clockCollection.get(j) == 60) {
}
System.out.println(clockCollection.get(j));
System.out.println("---");
}
}
}
I would like to make the code upgrade na system.out hour IF there would be 60 minutes (raise hour and reset minutes to 00).
You can create a private method checkMinutes() that you will call inside of the Clock class every time you add minutes in one of the class's methods (for example if you made an addFiveMinutes().
public int addOneMinute(){
minutes++;
checkMinutes();
}
private void checkMinutes(){
if (minutes >= 60)
{
hours++;
minutes = minutes - 60;
}
}
//Having the private check method makes it simple to expand functionality in the future like so
public int addFiveMinutes(){
minutes = minutes + 5;
checkMinutes();
}
This will ensure the time rollovers to the correct amount as well, for example if minutes is 65 then the new minutes will be 5.
Now every time you call addOneMinute() in your main method, you don't have to check for anything! It will all be done automatically every single time.

How to make my clock like this 03:05:01

I have project in java.
Create CTime class with the following specifications
Attributes: Hour, minute and second
Hour >=0 and <= 23, minute >=0 and <=59 , second >=0 and <= 59
Methods
Constructor that updates the CTime attributes
set and get methods for each attribute
tick method that add 1 second to the CTime object and returns nothing
toString method that creates time string with the following format HH:mm:ss e.g. 22:15:01
and I did this
public class CTime {
int hour;
int min;
int sec;
public CTime(int h, int m, int s) {
hour = h;
min = m;
sec = s;
}
public void setHour(int h) {
hour = h;
}
public int getHour() {
return hour;
}
public void setMin(int m) {
min = m;
}
public int getMin() {
return min;
}
public void setSec(int s) {
sec = s;
}
public int getSec() {
return sec;
}
public void tick() {
sec++;
if (sec >= 59) {
sec = 0;
min++;
if (min >= 59) {
min = 0;
}
hour++;
}
}
public String toString() {
String s = hour + ":" + min + ":" + sec;
return s;
}
}
How to make my hour and min and sec with 2 digit, e.g. 05:02:09?
And my code is it correct or not?
If you insist on doing this kind of stuff with Strings the way you are, you could do something like the following:
public String toString() {
String s = (hour > 9 ? hour : "0" + hour) + ":" + (min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec);
return s;
}
Just use String.format()
public String toString() {
String s = String.format("%02d:%02d:%02d", hour, min, sec);
return s;
}
One more link here
And your code, yes it is correct. To make it a live clock, all you have to do is call tick() method every second. Take a look at this SO post to learn how to do that.

Mooc objects within objects

I'm working on the mooc.fi assignments and I'm really stuck at the clock assignment. I don't want a solution, but advice on how to reach my solution as I'm still learning and really need to figure out how to work through this. If you're unfamiliar with mooc, the current section is on how to work with objects within objects.
It consists of three classes, the main creates the clock and the boundedcounter is what makes the clock tick. I get it to print onto the screen, but when a custom starting input is entered it prints that first, then resets the value back to zero. Can someone point me in the right direction please? Sorry for the basic question, still trying to learn this java language!
Main
public class Main {
public static void main(String[] args) {
Clock clock = new Clock(23, 59, 50);
int i = 0;
while( i < 20) {
System.out.println( clock );
clock.tick();
i++;
}
}
}
Clock
public class Clock {
private BoundedCounter hours;
private BoundedCounter minutes;
private BoundedCounter seconds;
public Clock(int hoursAtBeginning, int minutesAtBeginning, int secondsAtBeginning) {
// the counters that represent hours, minutes and seconds are created and set to have the correct initial values
this.hours = new BoundedCounter(hoursAtBeginning);
this.hours.setValue(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.minutes.setValue(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
this.seconds.setValue(secondsAtBeginning);
}
public void tick() { //increases the time
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
if (this.minutes.getValue() == 0) {
this.hours.next();
}
}
}
public String toString() {
// returns the string representation
return hours + ":" + minutes + ":" + seconds;
}
}
BoundedCounter
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
// write code here
this.value = 0;
this.upperLimit = upperLimit;
}
public void next() {
// write code here
if (value < upperLimit) {
value++;
} else {
value = 0;
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
if (value >= 0 && value <= upperLimit) {
this.value = value;
}
}
#Override
public String toString() {
if (value < 10) {
return "0" + value;
}
return "" + value;
}
}
You're passing the current time to BoundedCounter.
this.hours = new BoundedCounter(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
But BoundedCounter is expecting the upper bound, not the current time.
public BoundedCounter(int upperLimit) {
Since whatever time you pass it is considered the upper limit, the next tick rolls over to 0:0:0.
BoundedCounter.next() sets value to 0 if value is not less than upperLimit. Since the Clock constructor always initializes all BoundedCounter value values to be equal to upperLimit, the first call to Clock.tick() will cause all BoundedCounter objects to set their value values to 0.
Besides the corrections:
this.hours = new BounedCounter(int upperLimit);
this.minutes = new BounedCounter(int upperLimit);
this.seconds = new BounedCounter(int upperLimit);
the method public void tick() has to be composed as shown below, otherwise when the value of the minutes is 00 while the value of the seconds is 01, 02, ...59, the value of the hours will be increased with every second, and the result will be 01:00:01, 2:00:02, 3:00:03, etc.
public void tick() {
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
}
if (this.minutes.getValue() == 0 && this.seconds.getValue() == 0) {
this.hours.next();
}
}

Java - creating an input limit for my constructor

I received an assignment for school where they ask me to build a simple clock with some functions.
I need some kind of constraint so that if i create an object people are only allowed to input good integers. For example; you are not allowed to enter 25 at hours or a integer higher then 60 at minutes and seconds.
I started creating instance variables for Hours, minutes and seconds. I created a constructor;
My code is below:
public class Clock{
//Instance variables
public int seconds;
public int minutes;
public int hours;
public Clock ( int InsertSeconds, int InsertMinutes, int InsertHours){
seconds = InsertSeconds;
minutes = InsertMinutes;
hours = InsertHours;
}
}
Ps; I am beginner at java, don't fire shots at me
Thanks!
Throw an exception. IllegalArgumentException would be a good choice.
public Clock ( int InsertSeconds, int InsertMinutes, int InsertHours){
if (InsertSeconds > 59 || InsertSeconds < 0) {
throw new IllegalArgumentException("InsertSeconds must be in range 0-59 but found "+ InsertSeconds);
}
// similar for minutes & hours
seconds = InsertSeconds;
minutes = InsertMinutes;
hours = InsertHours;
}
Use exceptions! For example:
if(seconds > 60)
throw new SecondsTooBigException();
And you'll have to create a new SecondsTooBigExcetion
public class SecondsTooBigException extends Exception {
#Override
public String getMessage() {
return super.getMessage() + "\nSecondsTooBigException: Exception occured, because you defined a value, which is not allowed for seconds";
}
}
Assuming your clock has a 24 hour format (i.e. a simple solution), you can use a basic flow control:
public boolean areAllSegmentsValid() {
if (this.hours < 0 || this.hours > 24) {
System.out.println("Hours are not in range 0-24");
// A better of option wil be exception (you are novice so learn about first)
return false;
} else if (this.minutes < 0 || this.minutes > 60){
System.out.println("Minutes are not in range 0-24");
// A better of option wil be exception (you are novice so learn about first)
} else if (this.seconds < 0 || this.seconds > 60){
System.out.println("Minutes are not in range 0-24");
// A better of option wil be exception (you are novice so learn about first)
} else {
return true;
}
return true;
}
The above solution requires you to have the minimum understanding of Java, which you already have pointed out in your original question. Once you grasp this concept, I suggest you try and use assertions to replace the if conditions above e.g.:
assert (this.hours >= 0 && this.hours<=24); // Assertion to check if the cond. is true
...
...
The more Java way is to use exceptions for your Clock class e.g. IllegalHoursValue exception, or IllegalTimeSegment exception. However, I will leave you here to investigate the rest for your safe.
You could use this static method:
public static boolean validTime(int hours, int minutes, int seconds) {
if (hours <= 24 && minutes <= 60 && seconds <= 60) {
if (hours >= 0 && minutes >= 0 && seconds >= 0) {
return true;
}
}
return false;
}
Give it the values that the user inputs. If it returns true then pass it to the constructor, otherwise ask the user to input the values again.

Categories