My code asks for the user to enter the day with an integer value ie Sunday = 0, Monday = 1, etc., then asks the user to input a number representing an offset day. From there the program finds the day corresponding to the offset number ie
Enter today's day: 0 //Sunday
Enter the number of days elapsed since today: 6
6 days from Sunday is Sunday
The problem with the above output is that since I'm using, "%6" to find the offset day, it skips one day for values 6.
Also, I can't figure a way to find the day for an entered negative offset value. ie
Enter today's day: 0 //Sunday
Enter the number of days elapsed since today: -2
-2 days from Sunday is Friday
Here's my code
import java.util.Scanner ;
public class test {
public static void main (String[] args) {
Scanner Input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int today = Input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int offset = Input.nextInt ();
int offsetDay = 0;
if (offset >= 0)
offsetDay = (today + offset)% 6 ; //to get remainder and make it vary from 0 - 6
else if (offset < 0)
offsetDay = (today - offset)% 6 ;
String todayText = null ;
String offsetText = null;
//Converting input integers into days in text for variable today
switch (today) {
case 0 : todayText = "Sunday" ; break;
case 1 : todayText = "Monday"; break;
case 2 : todayText = "Tuesday"; break;
case 3 : todayText = "Wednesday";break;
case 4 : todayText = "Thrusday"; break;
case 5 : todayText = "Friday"; break;
case 6 : todayText = "Saturday"; break;
}
//Converting input integers into days in text for variable offset
switch (offsetDay) {
case 0 : offsetText = "Sunday" ; break;
case 1 : offsetText = "Monday"; break;
case 2 : offsetText = "Tuesday"; break;
case 3 : offsetText = "Wednesday";break;
case 4 : offsetText = "Thrusday"; break;
case 5 : offsetText = "Friday"; break;
case 6 : offsetText = "Saturday"; break;
}
System.out.println(offset + " days from " + todayText + " is " + offsetText);
}
}
My last question is, how would I implement this using enumeration? Any thoughts?
Please, try this code snippet, maybe this will help you:
public class Days
{
enum DAY
{
MON("Monday"),
TUE("Tuesday"),
WED("Wednesday"),
THU("Thursday"),
FRI("Friday"),
SAT("Saturday"),
SUN("Sunday");
private String name;
private DAY(String name)
{
this.name= name;
}
#Override
public String toString()
{
return this.name;
}
public DAY add(int days)
{
int posMod = (this.ordinal() + days) % values().length;
if (posMod < 0)
{
posMod += values().length;
}
return DAY.values()[posMod];
}
}
public static void main(String[] args)
{
DAY a = DAY.values()[0];
System.out.println(a);
System.out.println(a.add(-2));
System.out.println(a.add(0));
System.out.println(a.add(-8));
}
}
You should use %7 instead of %6 as counting from 0-6 inclusive is 7.
Related
I need to know which day and day name is on a specific date. And somehow I made a mistake because for years with 19.. it works but at 2000 I can't get the right day anymore. For example if I use the date 9.1.2001 it doesn't say me the day, instead the error of the switch I made occurs.
and i shouldn't use the calendar methods
here is my code:
public class FindDay {
public static void main(String[] args) {
System.out.println("Type a day: ");
int day = In.readInt();
System.out.println("Type a month: ");
int month = In.readInt();
System.out.println("Type a year: ");
int year = In.readInt();
if(day < 1 || day > 32) {
System.out.println("Type valid day");
}else if (month < 1 || month >12) {
System.out.println("Type valid month");
}else if (year < 1900) {
System.out.println("Type valid year");
}
int wholeDaysYear; //to calculate how much days a year has
if (year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0) ) {
wholeDaysYear = 366;
}else {
wholeDaysYear = 365;
}
int monthDays = 0; //calculates days to this month
int february; //if February has 28 or 2 days
if(wholeDaysYear ==366) {
february = 29;
}else {
february = 28;
}
switch(month) {
case 1: monthDays= 0; break;
case 2: monthDays =31; break;
case 3: monthDays= 31+february; break;
case 4: monthDays= 31+february+31; break;
case 5: monthDays= 31+february+31+30; break;
case 6: monthDays= 31+february+31+30+31; break;
case 7: monthDays= 31+february+31+30+31+30; break;
case 8: monthDays= 31+february+31+30+31+30+31; break;
case 9: monthDays= 31+february+31+30+31+30+31+31; break;
case 10: monthDays= 31+february+31+30+31+30+31+31+30; break;
case 11: monthDays= 31+february+31+30+31+30+31+31+30+31; break;
case 12: monthDays= 31+february+31+30+31+30+31+31+30+31+30; break;
default: System.out.println("Enter valid month!");break;
}
int leapYear = ((year-1) / 4 - 474) - ((year-1) / 100 - 18) + ((year-1) / 400 - 4); //calculates the leap years
int allDays =(((year - leapYear)-1900)*wholeDaysYear)+monthDays+day-1; //Calculates all days
System.out.println(allDays);
int dayName = allDays % 7;
String dayNames = null; //gives the days their name
switch (dayName) {
case 1: dayNames = "Monday";break;
case 2: dayNames = "Tuesday";break;
case 3: dayNames = "Wendesday";break;
case 4: dayNames = "Thursday";break;
case 5: dayNames = "Friday";break;
case 6: dayNames = "Saturday";break;
case 7: dayNames = "Sunday";break;
default: System.out.println("Type valid Input");break;
}
System.out.println(dayNames);
}
}
You don't have to work so hard... assuming you have the day of the month, month of the year and full-year, you can simply do (example):
LocalDate ld = LocalDate.of(1999, 12, 12);
System.out.println(ld.getDayOfWeek()); // prints SUNDAY
LocalDate is available since Java 8.
As for your code, two bugs that are easy to spot are:
The cases in the switch go from 1 to 7 while they should go from 0 to 6 since you're calculating the reminder out of 7.
int dayName = allDays % 7; here you assume that the first day of the year is Monday (according to your case switch) which is not necessarily true.
You can try something like this:
Date yourDate;
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //or Calendar.DAY_OF_WEEK
// etc.
I'm trying to get the System.out.print on the same line. I want to have the cases as just days (case 0: "Sunday") so I can write System.out.println( "Today is "+ day + " and the future day is " + m1) but when I try this, I get the case number instead of the string (Today is 0 and the future day is 0). I think there's a better way to write the logic compared to the way I have it:
import java.util.*;
public class HomeWork3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Sun = 0, Mon = 1, Tue = 2, Wed = 3, Thurs = 4, Fri = 5, Sat = 6 ");
System.out.print("\nEnter today's number: ");
int day = input.nextInt();
System.out.print("Enter the number of days that elapsed since today: ");
int n1 = input.nextInt();
//String strD = Integer.toString(day);
switch (day){
case 0: System.out.println("Today is Sunday");
break;
case 1: System.out.println("Today is Monday");
break;
case 2: System.out.println("Today is Tuesday");
break;
case 3: System.out.println("Today is Wednesday");
break;
case 4: System.out.println("Today is Thursday");
break;
case 5: System.out.println("Today is Friday");
break;
case 6: System.out.println("Today is Saturday");
break;
}
int m1 = ((day + n1)% 7);
switch (m1){
case 0: System.out.println("The future day is Sunday");
break;
case 1: System.out.println("The future day is Monday");
break;
case 2: System.out.println("The future day is Tuesday");
break;
case 3: System.out.println("The future day is Wednesday");
break;
case 4: System.out.println("The future day is Thursday");
break;
case 5: System.out.println("The future day is Friday");
break;
case 6: System.out.println("The future day is Saturday");
break;
}
//String strD = Integer.toString(day);
//System.out.println(strD + " this might work " + n1);
}
}
OUTPUT:
Sun = 0, Mon = 1, Tue = 2, Wed = 3, Thurs = 4, Fri = 5, Sat = 6
Enter today's number: 2
Enter the number of days that elapsed since today: 5
Today is Tuesday
The future day is Sunday
How about the following:
String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int m1 = ((day + n1)% 7);
String output = String.format("Today is %s, the future day is %s", days[day], days[m1]);
System.out.println(output);
(Obviously you need to ensure day<7)
The easiest way is when you change the println() in the first switch-block to print() and add a space to your text.
A second version is to define two Strings and set the values in the switch-blocks:
String today;
switch (day){
case 0: today = "Sunday";
break;
and so on and also
String futureday;
switch (m1){
case 0: futureday = "Sunday";
break;
and so on. At last you have your desired output:
System.out.println("Today is "+ today + " and the future day is " + futureday);
But the most elegant way is to define an array of weekdays:
String[] days = {"Sunday","Monday","Tuesday"};
So you can delete your switch-blocks and simply write:
System.out.println("Today is "+ days[day] + " and the future day is " + days[m1]);
Hint: You have to initialize day and futureday. And you should check, that day is < 7 to prevent an IndexOutOfBounds-Exception.
How about simply using the built-in DayOfWeek enum:
int day = 4;
System.out.println("Today is " + DayOfWeek.of(day)
.getDisplayName(TextStyle.FULL, Locale.getDefault()));
Output:
Today is Thursday
But if you want to use a switch statement, I'd say, add a layer of abstraction, to simplify the problems you need to solve. e.g. make a method that takes and int and returns the day of the week as a String:
public static String getWeekDay(int dayNumber) {
switch(dayNumber) {
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
...
}
throw new IllegalArguemntException("Invalid day number: " + dayNumber);
}
And use that to create the output:
System.out.println("Today is " + getWeekDay(day));
Because you need to associate int and String you can use a map
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//add all days into the map with their key (number)
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "Sunday");
map.put(1, "Monday");
map.put(2, "Tuesday");
map.put(3, "Wednesday");
map.put(4, "Thursday");
map.put(5, "Friday");
map.put(6, "Saturday");
//Printing all days
for(int key : map.keySet()){
System.out.print(key+"="+map.get(key)+", ");
}
System.out.print("\nEnter today's number: ");
int day = input.nextInt();
System.out.print("Enter the number of days that elapsed since today: ");
int n1 = input.nextInt();
n1 = ((day + n1)% 7);
System.out.println("Today is "+map.get(day) + ", the future day is " + map.get(n1));
}
It allows you to get back the value which corresponds to the key entered with rhe scanner
I'm working on using enum / switch case along with Zeller's formula for saying what day of the year a specific date will be. My code was printing the right days before I implemented the enum / switch portion of my code (below). After I put in the enum/ switch case, when I run it in DrJava it does prompt for the day, the month and the year, but nothing prints once it goes through the switch case
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
DetermineDay(value); // Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0)
+ (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
}
public static String DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
return result;
}
}
If you want to output the day using DetermineDay you need to call that method at the end after you did the calculation and assigned the result to value.
This seems to work but there is a problem in your algorithm when trying this program with the date 4/11/2016 it does find that it is a Friday, but when using the date 5/5/2016 which is today the output is ¨Looks like that day doesn't exist¨, so yeah there is that.
At the end of DetermineDay you dont need to return a result since you already sop the result inside the switch.
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0) + (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
DetermineDay(value);
}
public static void DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
}
}
We're supposed to make a program in computer science that figures out what day of the week you were born on. We were given these instructions.
1) Start with the last two digits of the year in which you were born.
2) Divide the above number by 4, dropping the remainder if there is one.
3) Find the number associated with the month in which you were born in the Table of Months.
4) On which day of the month is your birthday?
5) Find the sum of the four numbers obtained in steps 1 through 4.
6) Divide the sum by the number 7. The day that corresponds to the remainder in the Table of Days is the day of the week you were born on.
Table of Months Table of Days
January 1 (0 in leap year) Sunday 1
February 4 (3 in leap year) Monday 2
March 4 Tuesday 3
April 0 Wednesday 4
May 2 Thursday 5
June 5 Friday 6
July 0 Saturday 0
August 3
September 6
October 1
November 4
December 6
I've been having trouble with is incomparable types: int and boolean, i don't know what the problem is, ive tried changing variables to boolean, but it doesn't solve anything.
package LeapYear;
import java.util.*;
public class Birthday
{
static Scanner in= new Scanner(System.in);
public static void main (String []args)
{
int year=getYear();
int month=getMonth(year);
int day=getDay();
int total=computeDay(day, month, year);
int dayofbirth=dayOfWeek(day,month,year);
}//end main
public static int getYear()
{
System.out.println("Please enter the last two digits of the year you were born:");
int y=in.nextInt();
return y;
}
public static int getMonth(int year)
{
int m;
System.out.println("Please select the month in which you were born:"+
"1.)Januaryn\n"+
"2.)February\n"+
"3.)March\n"+
"4.)April\n"+
"5.)May\n"+
"6.)June\n"+
"7.)July\n"+
"8.)August\n"+
"9.)September\n"+
"10.)October\n"+
"11.)November\n"+
"12.)December\n");
m=in.nextInt();
System.out.println("You entered " + m);
switch(m)
{
case 1: if(year ==true)
return 0;
else
return 1 ;
break;
case 2:if(year == true)
return 3;
else
return 4;
break;
case 3:return 4;
break;
case 4:return 0;
break;
case 5:return 2;
break;
case 6:return 5;
break;
case 7:return 0;
break;
case 8:return 3;
break;
case 9:return 6;
break;
case 10:return 1;
break;
case 11:return 4;
break;
case 12:return 6;
break;
}//end case
}//end getMonth
public static int getDay()
{
int d;
System.out.println("Please enter the day on which you were born");
d=in.nextInt();
return d;
}//end getDay
public static int computeDay(int day, int month, int year)
{
int weekday;
int y2=year/4;
int m2= month + y2 + day;
int total=m2/7;
return total;
}//end computeDay
public static int dayOfWeek(int day, int month, int year, int total)
{
int dob;
switch(dob)
{
case 1:if (total=1)
System.out.println("You were born on a Sunday");
break;
case 2:if (total=2)
System.out.println("You were born on a Monday");
break;
case 3: if (total=3)
System.out.println("You were born on a Tuesday");
break;
case 4: if(total=4)
System.out.println("You were born on a Wednesday");
break;
case 5: if(total=5);
System.out.println("You were born on a Thursday");
break;
case 6: if (total=6);
System.out.println("You were born on a Friday");
break;
case 7: if (total=7);
System.out.println("You were born on a Saturday");
break;
}
}//end dayOfWeek
}//end class
if(year == true) cannot compile because an integer cannot be true. Do something useful with that statement like:
if(year < 50)
{
System.out.println("Wow, you're old!");
return 0;
}
Because you are only getting the last two digits of their year of birth, you will have trouble deciding if the user was born in the year 1905 or 2005. This is an unlikely case, but you would not be able to decipher whether the user was born this century or the last. If it is acceptable not to know, don't change it. If not, you will need to get more information from the user.
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