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.
Related
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);
}
}
I have this code here:
But I get the error message:
The operator < is undefined for the argument type(s)LocalTime, int
Why is that? How can I fix the code?
Here is the code again as text:
import java.time.LocalTime;
public class Services {
public static void main(String[] args){
LocalTime t = LocalTime.now();
if (t >=0 && t<12){
System.out.println("Good Morning!");
}
else if (t>=12 && t<18)
{
System.out.println("Good Afternoon!");
}
else{
System.out.println("Hello Neel ,how may I help you");
}
}
}
Comparing objects
You can not use < on anything else than primitives like int. Use compareTo instead.
Like first.compareTo(second), the result is either
negative (if smaller),
0 (if equals) or
positive greater 0 (if greater).
So the equivalent of to first < second would be first.compareTo(second) < 0.
Comparing LocalTime in particular
For the java.time API, there are also special methods like isBefore and isAfter which make this comparison even simpler.
LocalTime vs int
Also, you can not compare a high level object such as LocalTime to a plain int. Have a look at
LocalTime.of(12, 0)
and similar methods instead.
There are also some special pre-created constants, such as LocalTime.MIDNIGHT and LocalTime.NOON.
Putting everything together
If you follow both advices, the fixed code could look like:
LocalTime t = LocalTime.now();
if (t.isAfter(LocalTime.MIDNIGHT) && t.isBefore(LocalTime.NOON)) {
System.out.println("Good Morning!");
} else if (t.isAfter(LocalTime.NOON) && t.isBefore(LocalTime.of(18, 0))) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel, how may I help you");
}
Ideally you could also introduce a quick helper method such as
private static boolean isBetween(LocalTime start, LocalTime time, LocalTime end) {
return time.isAfter(start) && time.isBefore(end);
}
to simplify the code further:
LocalTime t = LocalTime.now();
if (isBetween(LocalTime.MIDNIGHT, t, LocalTime.NOON)) {
System.out.println("Good Morning!");
} else if (isBetween(LocalTime.NOON, t, LocalTime.of(18, 0))) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel, how may I help you");
}
The straightforward way to translate your code into something that works is
LocalTime t = LocalTime.now();
int h = t.getHour();
and then compare 'h'.
For more complicated cases, for example if you wanted to check whether it was before 12:30, look into constructions like
t.isBefore(LocalTime.of(12, 30))
or possibly
!LocalTime.of(12, 30).isAfter(t);
(The two differ in the decision of the exact time 12:30)
Well this was very useful! I'm a beginner myself and was playing around with the if statements. With the help of the answers I managed to scramble something simple:
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
System.out.println("The current time is "+currentTime);
int hour = currentTime.getHour();
int timeOfDay = 10;
if (hour >= 0 && hour < 12) {
System.out.print("Good Morning!");
} else if (hour >= 12 && hour < 18) {
System.out.print("Good Afternoon!");
} else {
System.out.print("Good Evening!");
}
}
}
since "isBetween" did not work in the Main Class
public static void main(String[] args) {
LocalTime t = LocalTime.now();
int h = t.getHour();
if (h >= 0 && h < 12) {
System.out.println("Good Morning!");
} else if (h >= 12 && h < 20) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel ,how may I help you");
}
}
}This worked for me
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();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following code that I am trying to get working for a project in a class that I am in. I will also include the requirements
Design and implement the class Day that implements the day of the week in a program. The class Day should store the day, such as Sun for Sunday. The program should be able to perform the following operations on an object of type Day:
A. Set the day.
B. Print the day.
C. Return the day.
D. Return the next day.
E. Return the previous day.
F. Calculate and return the day by adding certain days to the current day. For example, if the current day is Monday and we add four days, the day to be returned is Friday. Similarly, if today is Tuesday and we add 13 days, the day to be returned is Monday.
G. Add the appropriate constructors.
H. Write the definitions of the methods to implement the operations for the class Day, as defined in A through G.
I. Write a program to test various operations on the class Day.
The code is as follows:
`import java.util.*;
class Day {
private int dayValue;
private static final int INVALID = -1;
public Day() { this.dayValue = INVALID; }
public Day(String day) { setDay(day); }
public Day(int day) { this.dayValue = (day<0 || day>6) ? INVALID : day; }
public void setDay(String day) {
if(day.equals("sunday") || day.equals("Sun")) {
this.dayValue = 0;
} else if(day.equal("monday") || day.equals("Mon")) {
this.dayValue = 1;
} else if(day.equals("tuesday") || day.equals("Tues")) {
this.dayValue = 2;
} else if(day.equal("wednesday") || day.equals("Wed")) {
this.dayValue = 3;
} else if(day.equals("thursday") || day.equals("Thurs")) {
this.dayValue = 4;
} else if(day.equal("friday") || day.equals("Fri")) {
this.dayValue = 5;
} else if(day.equal("saturday") || day.equals("Sat")) {
this.dayValue = 6;
} else {
this.dayValue = INVALID;
}
}
public String getDay() {
if (dayValue==0) { return "Sunday"; }
if (dayValue==1) { return "Monday"; }
if (dayValue==2) { return "Tuesday"; }
if (dayValue==3) { return "Wednesday"; }
if (dayValue==4) { return "Thursday"; }
if (dayValue==5) { return "Friday"; }
if (dayValue==6) { return "Saturday"; }
return "\"I don't know what day it is!\"";
}
public void printDay() {
System.out.println("When printing, your day is " + getDay()); //displays the day at the time of printing.
}
// Next Day
public String getNextDay()
{
// the compareTo() method allows us to set saturday as Sat, Sunday to Sun, etc
if((day.compareTo("sunday") == 0) || (day.compareTo("Sun") == 0))
return ("Monday");
else if((day.compareTo("monday") == 0) || (day.compareTo("Mon") == 0))
return ("Tuesday");
else if((day.compareTo("tuesday") == 0) || (day.compareTo("Tue") == 0))
return ("Wednesday");
else if((day.compareTo("wednesday") == 0) || (day.compareTo("Wed") == 0))
return ("Thursday");
else if((day.compareTo("thursday") == 0) || (day.compareTo("Thu") == 0))
return ("Friday");
else if((day.compareTo("friday") == 0) || (day.compareTo("Fri") == 0))
return ("Saturday");
else if((day.compareTo("saturday") == 0) || (day.compareTo("Sat") == 0))
return ("Sunday");
else
return ("\"I don't know what day it is!\"");
}
// Previous day
public String getPreDay()
{
if((day.compareTo("sunday") == 0) || (day.compareTo("Sun") == 0))
return ("Saturday");
else if((day.compareTo("saturday") == 0) || (day.compareTo("Sat") == 0))
return ("Friday");
else if((day.compareTo("friday") == 0) || (day.compareTo("Fri") == 0))
return ("Thursday");
else if((day.compareTo("thursday") == 0) || (day.compareTo("Thu") == 0))
return ("Wednesday");
else if((day.compareTo("wednesday") == 0) || (day.compareTo("Wed") == 0))
return ("Tuesday");
else if((day.compareTo("tuesday") == 0) || (day.compareTo("Tue") == 0))
return ("Monday");
else if((day.compareTo("monday") == 0) || (day.compareTo("Mon") == 0))
return ("Sunday");
return ("\"I don't know what day it is!\"");
}
public Day calcDay(int offset) { /* your code here */ }
// extra good for printin
public String toString() { return getDay(); }
}
// main execution point
public static void main (String args[]) {
{
// One of its weakness is the case sensitive: sun, Sunday, sunday, SuNdAy...
// need more codes to avoid this case sensitiveness...
// instantiate testday object of type MyDay class
// with "Sun" as initial value....
Day testday = new Day("Sun");
// prompt user to set his/her day
System.out.print("Enter day to set your day: ");
// read and store user's day
String storeday = readinput.nextLine().toLowerCase(); //Changes input into all lowercase to deal with variations
// invoke setDay() method to set a day defined by user
testday.setDay(storeday);
// invoke getDay() method to get a day
System.out.println("Your day is " + testday.getDay());
// test printing by invoking printDay() method
testday.printDay();
// invoke getPreDay() method to get the previous day
System.out.println("Your previous day is " + testday.getPreDay());
// invoke getNextDay() method to get the next day
System.out.println("Your next day is " + testday.getNextDay());
System.out.println("How many Days would you like to add? " + testday.calcNextDay());
}
}`
I am receiving the following error:
Day.java:92: error: class, interface, or enum expected
public static void main () {
^
Day.java:101: error: class, interface, or enum expected
System.out.print("Enter day to set your day: ");
^
Day.java:103: error: class, interface, or enum expected
String storeday = readinput.nextLine().toLowerCase(); //Changes input into all lowercase to deal with variations
^
Day.java:105: error: class, interface, or enum expected
testday.setDay(storeday);
^
Day.java:107: error: class, interface, or enum expected
System.out.println("Your day is " + testday.getDay());
^
Day.java:109: error: class, interface, or enum expected
testday.printDay();
^
Day.java:111: error: class, interface, or enum expected
System.out.println("Your previous day is " + testday.getPreDay());
^
Day.java:113: error: class, interface, or enum expected
System.out.println("Your next day is " + testday.getNextDay());
^
Day.java:115: error: class, interface, or enum expected
System.out.println("How many Days would you like to add? " + testday.calcNextDay());
^
Day.java:116: error: class, interface, or enum expected
}
^
10 errors
Originally my code looked like this
public class Day
{
static Scanner readinput = new Scanner(System.in);
String day;
public Day(String day)
{
day = "Sunday";
}
// set the day
public void setDay(String theDay)
{
day = theDay;
}
public String getDay()
{
return day;
}
public void printDay()
{
System.out.println("When printing, your day is " + day);
}
Why not use arrays?
With an array, you could handle things in a more concise and simple way.
String[] dayOfWeekShortNames = new String[] {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
String[] dayOfWeekLongNames = new String[] {
"Sunday", "Monday", "Wednesday", "Thursday", "Friday", "Saturday"
};
Then, simply validate whether the value passed in parameter is correct.
public void setDay(String dayOfWeek) {
if (dayOfWeek == null || (0 < dayOfWeek.length() && dayOfWeek.trim().length() == 0))
throw new IllegalArgumentException("dayOfWeek cannot be null or white space.");
for (int i = 0; i < dayOfWeek.length(); i++)
if (dayOfWeek.charAt(i).isDigit())
throw new IllegalArgumentException("dayOfWeek cannot be numeric.");
if (dayOfWeek.length() < 3) // for short names
throw new IllegalArgumentException("dayOfWeek must be at least 3 characters long.");
for (int i = 0; i < dayOfWeekShortNames.length && i < dayOfWeekLongNames.length; i++)
if (dayOfWeekShortNames[i].toLowerCase() == dayOfWeek.ToLowerCase()
|| dayOfWeekLongNames[i].toLowerCase() == dayOfWeek.ToLowerCase()) {
dayValue = i;
return;
}
throw new IllegalArgumentException(
"Day of week: " + dayOfWeek + " could not be found.");
}
This is just a simple example off the top of my head.
Why not use a Program class?
Instead of just writing the main() method out of nowhere which can lead to multiple compile-time errors, perhaps one great deal would be to locate your main method inside a Program class so that it is a member of a class, and the compiler shall no longer complaint. Furthermore, the advantage of doing so shall make it obvious, at least at some extent, that your program entry point is there. This Program class shall contain nothing more than the main() method.
public class Program {
public static void main(String args[]) {
// You code here...
}
}
As for the user inputs, perhaps using the Console class... Here's an example on how to use it.
I/O from the Command Line
Disclaimer
I have not tested this code and is provided as-is for example purposes only. I am not a Java expert, and I did my best off the top of my head to help.
EDIT
I did not use an array because I wanted to store the value as a string and not the index.
In fact, the code sample in your question stores the day of week in an integer value as per this line:
private int dayValue;
Hence the assignments when you set the day as follows:
public void setDay(String day) {
if (day == "sunday" || day == "Sun")
dayValue = 0;
else if (day == "monday" || day == "Mon")
dayValue = 1;
...
}
The above actually stores the day of week in an integer format which shall satisfy most of any systems which is going to use days of week. Plus, you cannot guarantee the exact syntax of a string input by the user so that even if you either compare day == "sunday" or day == "Sun", you would have to adjust your casing according to the string you're expecting in your setDay() function, which in my opinion doesn't make sense.
The most common practice for such behaviour playing around with days of week, etc. is to use arrays with the proper expected casing, then compare the input values with either uppercase or lowercase values for both, the input and the value from the array (only this can guarantee a perfect match), then you can store the index in you dayValue private member. Then, when retrieving the day of week through the getDay() function, you can simply write a single line of code which can assure you to work flawlessly, since you captured any potential errors while setting the input through the setDay() method.
public String getDay() { return dayOfWeekLongNames[dayValue]; }
And you shall get the name of the day of week previously set, instead of having to write if statements over and over again.
Another way to approach the problem is to use an enum for the days of the week. Here's a working example provided to show the general idea:
public class Day
{
enum DAY {
MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY(
"Saturday"), SUNDAY("Sunday");
public static DAY parse(final String value)
{
for (final DAY day : values())
{
if (day.description.equalsIgnoreCase(value) || day.description.substring(0, 3).equalsIgnoreCase(value))
{
return day;
}
}
return null;
}
private String description;
private DAY(final String description)
{
this.description = description;
}
#Override
public String toString()
{
return description;
}
}
public static void main(final String args[])
{
Day myDay;
myDay = new Day(DAY.SUNDAY);
System.out.println(myDay);
System.out.println(myDay.getPreviousDay());
System.out.println(myDay.getNextDay());
myDay = new Day("monday");
System.out.println(myDay);
System.out.println(myDay.getPreviousDay());
System.out.println(myDay.getNextDay());
myDay = new Day("wed");
System.out.println(myDay);
System.out.println(myDay.getPreviousDay());
System.out.println(myDay.getNextDay());
}
private final DAY day;
public Day(final DAY day)
{
this.day = day;
}
public Day(final String day)
{
this.day = DAY.parse(day);
}
public DAY getNextDay()
{
final DAY[] days = DAY.values();
return days[(day.ordinal() + 1) % days.length];
}
public DAY getPreviousDay()
{
final DAY[] days = DAY.values();
return days[((day.ordinal() - 1) + days.length) % days.length];
}
#Override
public String toString()
{
return day.toString();
}
}
"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;
}