Dealing with days of the week - java

I'm trying to write a program that counts through days of the week when given a number. I want to write this without using Arrays., or enum types, just methods How can I do this? I also want to be able to set a day of the week as starting point.
Thanks
public static void main(String[] args);
{
int sunday, monday, tuesday, wednesday, thursday, friday, saturday;
int week;
int day;
System.out.println(" Day of the week is" + day);
public void count()
public void week()
public void printday()
public void nextday()
public void previousday()
I'm not the best at this, but I figure practice makes perfect

This should do your trick, if i correctly understood your question :)
/**
*
* #param startingDay - day of the week starting point ( need to be between 0-6 )
* #param noDays number of days to count
* #return result Day of the week
*/
private static WeekDays getWeekDay(int startingDay, int noDays){
int dayNr = noDays % 7;
int finalDayNr = (startingDay + dayNr) % 7;
return WeekDays.values()[finalDayNr];
}
private static enum WeekDays {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
And the version with no ENUM, however the Enum version is desirable... from any point of view you might think of.
/**
*
* #param startingDay
* - day of the week starting point ( need to be between 0-6 )
* #param noDays
* number of days to count
* #return result Day of the week
*/
private static String getWeekDay(int startingDay, int noDays) {
int dayNr = noDays % 7;
int finalDayNr = (startingDay + dayNr) % 7;
return getDay(finalDayNr);
}
private static String getDay(int dayNr) {
switch (dayNr) {
case 0:
return "SUNDAY";
case 1:
return "MONDAY";
case 2:
return "TUESDAY";
case 3:
return "WEDNESDAY";
case 4:
return "THURSDAY";
case 5:
return "FRIDAY";
case 6:
return "SATURDAY";
}
throw new IllegalArgumentException("Wrong input. Day nr must be between 0-6.");
}
Usage sample ( for any of the two approach ):
public static void main(String[] args) {
System.out.println(getWeekDay(0, 15));
System.out.println(getWeekDay(1, 15));
System.out.println(getWeekDay(5, 3));
}

This looks like homework, but if you are not going to use arrays of days, I guess you can use a switch statement with the days of the week.
This particular sample iterates from day 3 (0 being Monday) to day 14 included.
for (int i = 3; i < 15; i++) {
String s = null;
switch (i % 7) {
case 0: s = "Monday"; break;
case 1: s = "Tuesday"; break;
case 2: s = "Wednesday"; break;
case 3: s = "Thursday"; break;
case 4: s = "Friday"; break;
case 5: s = "Saturday"; break;
case 6: s = "Sunday"; break;
}
System.out.println(s);
}

public static void main(String[] args) {
int day = 1;
System.out.println(isWeek(day));
printday(day);
}
public static boolean isWeek(int day) {
// Sunday or Saturday
if (day == 1 || day == 7) {
return false;
}
return true;
}
public static void printday(int day) {
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
// Until Saturday
default:
break;
}
}
Bad code but without arrays or enums someting like that ?

Related

How can i do input validations when user inputs values directly into objects?-JAVA

Is this possible to achieve or have i wrongly understood this question?
This is the question:
Implement a class MyDate that has integer data members to store month, day,
and year. The class should have a three-parameter constructor that allows the
date to be set at the time a new MyDate object is created. If the user creates a
MyDate object without passing any arguments, or if any of the values passed
are invalid, the default values of 1, 1, 2001 (i.e., January 1, 2001) should be
used. The class should have member functions to print the date in the following
formats:
3/15/10
March 15, 2010
15 March 2010
Demonstrate the usage of class MyDate by writing a class TestMyDate with a
main method that declares an object of type MyDate and displays it using all
the 3 formats.
Input Validation: Only accept values between 1 and 12 for the month, between
1 and 31 for the day, and between 1950 and 2020 for the year.
I've implemented this question but i can't seem to validate user input when the value is inserted at the time a new object is created. How can i do this? Please don't tell me to do research because i have done it. If Google could provide me with the answer i wouldn't have come here. Please help me.
Here's my codes:
The MyDate class:
package Number1;
public class MyDate {
private int month;
private int day;
private int year;
public MyDate()
{
month = 1;
day = 1;
year = 2001;
}
public MyDate(int m,int d,int y)
{
this.month = m;
this.day = d;
this.year = y;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
public void Format1()
{
int m,d,y,afterM;
m = getMonth();
d = getDay();
y = getYear();
afterM = y % 100;
System.out.println(""+m+"/"+d+"/"+afterM);
}
public void Format2()
{
int m,d,y;
String word = null;
m = getMonth();
d = getDay();
y = getYear();
switch(m)
{
case 1:
{
word = "January";
break;
}
case 2:
{
word = "February";
break;
}
case 3:
{
word = "March";
break;
}
case 4:
{
word = "April";
break;
}
case 5:
{
word = "May";
break;
}
case 6:
{
word = "June";
break;
}
case 7:
{
word = "July";
break;
}
case 8:
{
word = "August";
break;
}
case 9:
{
word = "September";
break;
}
case 10:
{
word = "October";
break;
}
case 11:
{
word = "November";
break;
}
case 12:
{
word = "December";
break;
}
default:
{
System.out.println("Please enter a number between 1-12");
break;
}
}
System.out.println(""+word+" "+d+","+y);
}
public void Format3()
{
int m,d,y;
String word = null;
m = getMonth();
d = getDay();
y = getYear();
switch(m)
{
case 1:
{
word = "January";
break;
}
case 2:
{
word = "February";
break;
}
case 3:
{
word = "March";
break;
}
case 4:
{
word = "April";
break;
}
case 5:
{
word = "May";
break;
}
case 6:
{
word = "June";
break;
}
case 7:
{
word = "July";
break;
}
case 8:
{
word = "August";
break;
}
case 9:
{
word = "September";
break;
}
case 10:
{
word = "October";
break;
}
case 11:
{
word = "November";
break;
}
case 12:
{
word = "December";
break;
}
default:
{
System.out.println("Please enter a number between 1-12");
break;
}
}
System.out.println(""+d+" "+word+" "+y);
}
}
The main TestMyDate:
package Number1;
public class TestMyDate {
public static void main(String[] args) {
MyDate D = new MyDate(7,23,2013);
D.Format1();
System.out.println();
D.Format2();
System.out.println();
D.Format3();
}
}
These codes only returns the dates in these different formats. Thanks for trying to help.
I think you can do the validation and throw new IllegalArgumentException("illegal date") in MyDate() to make all the client code strictly conform the rule:
public MyDate(int m,int d,int y)
{
// do some validate here
if (!validate(m, d, y))
throw new IllegalArgumentException("illegal date")
this.month = m;
this.day = d;
this.year = y;
}
private boolean validate(int m, int d, int y){
// use here as the central place of your validation (Format1(), Format2(), Format3(), ...)
}
I suggest you
input the values you need to read
validate the inputs are you go.
only once you have valid data create the object.
I suggest you don't use a class to input it's own values. This is making the class overly complicated.
I also suggest you use arrays instead of long switch statements. You can replace your switch statements with two lines of code.
You need to run your validation in the constructor before assigning them to the member variables. Your best bet would be to create private methods that return a bool so you can reuse the logic in the event that you add setters to those properties.
public MyDate(int m, int d, int y)
{
if (monthIsValid(m)) {
this.month = m;
}
if (dayIsValid(d)) {
this.day = d;
}
if (yearIsValid(y)) {
this.year = y;
}
}
Having the switch statement is fine, though I'd only have it in a single place, and call it from both Format methods.

Custom exceptions not working

I am trying to create two exceptions, one that is thrown when the month number is greater than 12 or less than 1, and another that is thrown when the month name is invalid. I thought that I included all the necessary steps ( I'm bad at exceptions ), but my main class is still not working. Any insight as to what I did wrong?
public class Month {
private int monthNumber;
/**
* Creates a new month set to January
*/
public Month(){
monthNumber = 1;
}
/**
* Creates a month set to the month number provided by the user
* #param m the number of the month
*/
public Month(int m) throws MonthsNumberException{
if (m<1 || m>12){
throw new MonthsNumberException("Number has to be greater than 1 and less than 12");
}else{
monthNumber = m;
}
}
/**
* Creates a month based on the string name provided
* #param m String values for the name of the month
*/
public Month(String m) throws MonthsNameException{
switch(m){
case "January":
monthNumber = 1;
break;
case "February":
monthNumber = 2;
break;
case "March":
monthNumber = 3;
break;
case "April":
monthNumber = 4;
break;
case "May":
monthNumber = 5;
break;
case "June":
monthNumber = 6;
break;
case "July":
monthNumber = 7;
break;
case "August":
monthNumber = 8;
break;
case "September":
monthNumber = 9;
break;
case "October":
monthNumber = 10;
break;
case "November":
monthNumber = 11;
break;
case "December":
monthNumber = 12;
break;
default:
throw new MonthsNameException("Invalid month name: " + m);
}
}
/**
* changes the month to the number provided
* #param m the number of the month
*/
public void setMonthNumber(int m) throws MonthsNumberException{
if (m<1 || m>12){
throw new MonthsNumberException("Number has to be greater than 1 and less than 12");
}else{
monthNumber = m;
}
}
/**
* returns the number of the month
* #return the number of the month
*/
public int getMonthNumber(){
return monthNumber;
}
/**
* returns the name of the month
* #return the name of the month
*/
public String getMonthName(){
String month="";
switch(monthNumber){
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
}
return month;
}
/**
* returns a string representation of the month
* #return the name of the month
*/
public String toString(){
return getMonthName();
}
/**
* if the two items are the same returns true
* #param m the month object to compare
* #return true if they are the same, false if not
*/
public boolean equals(Month m){
if (m.getMonthNumber() == this.getMonthNumber()){
return true;
}else{
return false;
}
}
/**
* If this calling item is after the month object passed as argument returns true
* #param m the month object
* #return true if calling object greater, false of argument greater
*/
public boolean greaterThan(Month m){
if (this.getMonthNumber()>m.getMonthNumber()){
return true;
}else{
return false;
}
}
/**
* If this calling item is before the month object passed as argument returns true
* #param m the month object
* #return true if calling object less than, false of argument less than
*/
public boolean lessThan(Month m){
if (this.getMonthNumber()<m.getMonthNumber()){
return true;
}else{
return false;
}
}
class MonthsNumberException extends Exception
{
public MonthsNumberException(String message)
{
super(message);
}
}
class MonthsNameException extends Exception
{
public MonthsNameException(String message)
{
super(message);
}
}
}
import javax.swing.*;
public class MonthDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String response = JOptionPane.showInputDialog(null, "Please enter a month number");
int mNumber = Integer.parseInt(response);
Month m1 = new Month(mNumber);
JOptionPane.showMessageDialog(null, m1.toString());
response = JOptionPane.showInputDialog(null, "Please enter a month name");
Month m2 = new Month(response);
JOptionPane.showMessageDialog(null, m2.toString());
}
}
Problem #1: You have to throw exceptions where Month is changed.
Problem #2: You are not allowed to catch the exception in the Main
method.
After fully understanding your homework I have a shortened solution for you. When you extend Exception this is called a "checked" Exception which means you HAVE to surround it in a try catch, but if you extend RuntimeException(also Error) it will allow you to execute the method in the Main thread without handling it. The consequence of this is your program will shutdown if the Exception is thrown, but that seems to be the desired result of your homework. Take your code as it is in your original question and just change this.
#SuppressWarnings("serial")
class MonthsNumberException extends RuntimeException {
public MonthsNumberException(String message) {
super(message);
}
}
#SuppressWarnings("serial")
class MonthsNameException extends RuntimeException {
public MonthsNameException(String message) {
super(message);
}
}
This should resolve your homework problem.
Haven't tried your code, and as you haven't told us the exact error, I am simply guessing here.
You have mentioned that the line Month m2 = new Month(response); is having problem.
Month(int) constructor is throwing a checked exception. However, your main method, which is the caller of this constructor, is not doing any proper handling. You should either catch it, or declare your main method to throws MonthsNumberException.
And please, don't simply throw out a big piece of code and "ask" question like this. There are lot of things you should do:
Have a simplified program to verify your understanding, and to demonstrate your problem. How is the lessThan method relates to the problem? You should remove all those "noise" from your question so that people can stay focus in your problem
You should give enough information. If there is an error, tell us the error message, or symptoms of the problem. Just throw out a big piece of code is not helping.

Java Calendar Program

I have a project due soon. We have to write a program that asks for a year and prints out a calendar. We can only use one while, one for, and one switch loop. (and no arrays! ugh) Im having trouble figuring out how to print out the days of each month, starting with the first day of the first week, as most months will not start on Sunday.
import java.util.*;
import java.util.Calendar;
class Lab2 {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.print("What year do you want to view? ");
int year = user.nextInt();
System.out.printf("%12d\n", year);
System.out.println();
boolean leap = isLeap(year);
int firstDay = JulianDate(year);
monthLoop(year, firstDay, leap);
}
public static boolean isLeap(int year) {
boolean verdict = false;
if (year % 100 == 0 && year % 400 == 0) {
verdict = true;
}
if(year % 100 != 0 && year % 4 == 0) {
verdict = true;
}
return verdict;
}
public static int JulianDate(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
public static void monthLoop(int year, int firstDay, boolean leap) {
for(int i=1; i <= 12; i++) {
switch (i) {
case 1: System.out.printf("%13s\n", "January");
break;
case 2: System.out.printf("%13s\n", "February");
break;
case 3: System.out.printf("%12s\n", "March");
break;
case 4: System.out.printf("%12s\n", "April");
break;
case 5: System.out.printf("%11s\n", "May");
break;
case 6: System.out.printf("%11s\n", "June");
break;
case 7: System.out.printf("%11s\n", "July");
break;
case 8: System.out.printf("%13s\n", "August");
break;
case 9: System.out.printf("%14s\n", "September");
break;
case 10: System.out.printf("%13s\n", "October");
break;
case 11: System.out.printf("%14s\n", "November");
break;
case 12: System.out.printf("%14s\n", "December");
break;
}
System.out.println("S M Tu W Th F S");
}
}
}
You would get the day of the week, as in this post, of the first day of the month and then start the counter from there.
How to get the day of the week in Java
For instance, if the day of the week was 5, you would put 4 "blanks" before the first date. The trick is that when you are doing your mod, to determine if there should be a new line, it would be
(dayofMonth + firstDayOfWeekOfMonth) % 7

Java class for Month Object

I'm working on a Java class for a Month object but it does not return the actual month, can you help?
Here is the Private methods class:
public class Month
{
private static int numInstantiated = 0;
private int monthNumber = 0;
public Month()
{
monthNumber = 1;
numInstantiated++;
}
public Month(int num)
{
monthNumber = num;
numInstantiated++;
}
public void setMonth(int newMonth)
{
monthNumber = newMonth;
}
public int getMonth()
{
return monthNumber;
}
public String toString()
{
switch(monthNumber)
{
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "No month specified";
}
}
}
And here is the main:
import java.util.Scanner;
public class UseMonth
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
Month m1 = new Month();
Integer newMonth;
//kbd.nextLine();
System.out.print("Please enter a numeric representaion of the Month? (ex. 1 for January)");
newMonth = kbd.nextInt();
m1.setMonth(newMonth);
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.getMonth());
}
}
Thanks in advance - Fred
Well, you're calling getMonth() which returns an int. You'll want to call m1.toString(), which returns the string representation you're trying to print.
This would be a perfect opportunity to use an enum:
enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December;
public static Month get(int n) {
return Month.values()[n-1];
}
}
public void test() {
for (int i = 1; i <= 12; i++) {
System.out.println("Month " + i + " = " + Month.get(i));
}
}
try this..
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString());
in your main class.
You have ovewritten the toString method. If you just call your getMonth method, this one does not call automatically the toString method, so it will return the number of the month.
If you want yo see the name of the month, you must do one of this two options:
Change your getMonth method:
public String getMonth()
{
return this.toString(monthNumber);
}
Or in your main method, change the System Out call:
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString(m1.getMonth()));
Hope it helps!!
Replace the final line of your code with this :
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString());
In your existing code, m1.getMonth() will return you the number of the month.
Using m1.toString() will give the respective String equivalent of the entered Integer number.
Hope this helps.
I think all the previous answers are correct and have provided you with a good feedback/answers. There's more than one way to skin a cat. So, I have cleaned up your code a and remove some of the unnecessary method and I have also tested the program to make sure it works for you. Here are the the two classes for you.
public class Month {
private static int numInstantiated = 0;
public Month() {
numInstantiated++;
getMonthTextual(numInstantiated);
}
public String getMonthTextual(int monthNumber) {
switch (monthNumber) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
return "No month specified";
}
}
}
here is the main class:
import java.util.Scanner;
public class test {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
Month m1 = new Month();
Integer newMonth;
//kbd.nextLine();
System.out.print("Please enter a numeric representaion of the Month? (ex. 1 for January)");
newMonth = kbd.nextInt();
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.getMonthTextual(newMonth));
}
}

Helper methods and using the for loop correctly

The guidelines for this program follow
Problem B: Year Dates. Objectives: Understanding the Switch structure, helper methods, and using a While loop with a sentinel value.
You are to make a class called Year2012 to manipulate dates when given a month(mm), or a month plus a day(dd) as integer values. It has the following get methods: 1) MonthName which returns a String value that is the name of the Month, e.g. September, June, May, etc. 2) DaysInMonth which returns the number of days in the month. 3)DayOfTheYear which returns the ordinal year date (a number between 1-365, often called the Julian date). Hint, use a for loop to add the days in each prior month, and then add the current month's days. 4) DayOfWeek which returns a String value which is the name of the day, e.g. Monday, Tuesday, etc.
Some of these methods can be used as 'helper' methods for others. All methods will use a switch statement either directly or indirectly. Each method computes a return value from the values sent to it, therefore there are no class attributes, and only a default constructor. All logic must be contained in your own methods. (ie. You will not use existing API classes for your logic.)
Design a tester application that asks the user for a month and day, and then displays the name of the month, the number of days in the month, the day of the week for this date, and the Julian date for this day. Write your program to process dates using a While loop until a sentinel value is entered. Run your program multiple times to test out different days, but turn in a final run using the following five dates: Jan.1, Apr.18, Aug.2, Nov.28, & Dec.15.
I'm having troubles with certain parts of this program. Specifically with the Julian date method and the dayofTheWeek method. Julian date keeps printing out a 1 (I haven't tested many dates), and is a helper method to the dayofTheWeek method, could you take a look at my code and see what my problem is?
public String monthName(int month)
{
String mon = null;
switch (month)
{
case 1:
mon = "January";
break;
case 2:
mon = "February";
break;
case 3:
mon = "March";
break;
case 4:
mon = "April";
break;
case 5:
mon = "May";
break;
case 6:
mon = "June";
break;
case 7:
mon = "July";
break;
case 8:
mon = "August";
break;
case 9:
mon = "September";
break;
case 10:
mon = "October";
break;
case 11:
mon = "November";
break;
case 12:
mon = "December";
break;
default:
mon = "Inccorect entry";
break;
}
return mon;
}
public int daysInMonth(int month)
{
int days = 0;
switch (month)
{
case 1:
days = 31;
break;
case 2:
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
days = 0;
}
return days;
}
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count == month; count++)
{
julian += daysInMonth(count);
}
return julian;
}
public String dayOfWeek(int month, int day)
{
int daysSoFar = dayOfTheYear(month, day);
int weekDay = daysSoFar % 7;
String dayName = null;
switch (weekDay)
{
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Incorrect entry";
}
return dayName;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Year2012 year = new Year2012();
System.out.println("Please enter a month using integers (Jan = 1): ");
int month = keyboard.nextInt();
System.out.println("Please enter a day within that month: ");
int day = keyboard.nextInt();
System.out.println("Month: " + year.monthName(month));
System.out.println("Number of days in month: " + year.daysInMonth(month));
System.out.println("Day of the week: " + year.dayOfWeek(month, day));
System.out.println("Julian date: " + year.dayOfTheYear(month, day));
}
}
You got it wrong in the for loop setting the julian value. Try this:
int julian = 0;
for (int count = 1; count < month; count++)
{
julian += daysInMonth(count);
}
return julian + day;
This loop uses count < month instead of count == month. It also returns julian + day.
You have a couple issues in the julian value calculation. Try this:
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count < month; count++) //note this loop will not run for Jan(as the logic below will cover that
{
julian += daysInMonth(count);
}
julian += day;
return julian;
}
This loop uses count < month instead of count == month, and then adds the days from the input before returning the answer.
note this loop will not run for Jan as in that case you just want to add the days entered.
Your for loop condition is count == month.
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count == month; count++)
{
julian += daysInMonth(count);
}
return julian;
}
This means the loop body will only execute when the month input is 1, and then only once. Did you mean count < month?

Categories

Resources