Java Date find day - java

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.

Related

How to use strings as the same as inputting int?

import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:")
int year = input.nextInt(); enter code here
System.out.print("Enter a month:");
int month = input.nextInt(); enter code here
int days = 0;
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
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:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " +days+ " Days in Month "+month+ " of Year " +year+ ".\n";
System.out.println(response); // new line to show the result to the screen.
}
}
Why can't I type in January to get the same output result if I type 1? It should print "There are 31 days in the month of January of Year 2018" I initialized the month so it should read January or any other month.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
You can use Strings in a switch statement to check for several equivalent cases:
switch (monthInput.toLowerCase()) {
case "january":
case "jan":
case "1":
days = 31;
break;
case "february":
case "feb":
case "2":
days = isLeapYear ? 29 : 28;
break;
case "march":
case "mar":
case "3":
days = 31;
break;
// etc.
default:
System.out.println(monthInput + " is not a valid month");
input.close();
System.exit(0);
}
But this means you have to read your input as a String, not as an int...
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); // enter code here
input.nextLine(); // read the rest of the line (if any)
System.out.print("Enter a month:");
String monthInput = input.nextLine();
Note the use of input.nextLine(); after the .nextInt() — this is because the nextInt() call does not consume all of the input, it only reads the int that you typed for the Year, it does not read the newline (enter key), so you have to read that to be ready to read the next input, which is the month number or name.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
A simple approach is to use name array
// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
// inside main
String monthStr = MONTH[month];
Add the full month names as needed.

Java - Method program - using switch case with method

I'm writing a program that takes in the users birth information, year, month, day, hour, minute. The program is the following:
Use the getRangedInt method to input the year (1965-2000), month
(1-12), Day*, hours (1 – 24), Minutes (1-59) of a person’s birth.
Note: use a switch() conditional selector structure to limit the user
to the correct number of days for the month they were born in. For
instance if they were born in Feb [1-29], Oct [1-31]. HINT: there are
only a few groups here not 12 different ones!
I'm absolutely confused with the day part. I have managed to get everything else to work except understand what I'm supposed to do for the day.
My code:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = true;
Scanner in = new Scanner(System.in);
while(done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", day, day);
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
The getIntInRange just does a basic input to get the number in range.
I'm confused because I don't know how to do the range for the day since there is also supposed to be a switch used.
This is a very strange requirement.
It looks like what is requested from you looks like something like this:
int numberOfDays;
switch (month) {
case 1: // $FALL-THROUGH
case 3: // $FALL-THROUGH
case 5: // $FALL-THROUGH
case 7: // $FALL-THROUGH
case 9: // $FALL-THROUGH
case 11:
numberOfDays = 31;
break;
case 4: // $FALL-THROUGH
case 6: // $FALL-THROUGH
case 8: // $FALL-THROUGH
case 10: // $FALL-THROUGH
case 12:
numberOfDays = 30;
break;
case 2:
numberOfDays = (0 == year / 4) ? 29 : 28;
break;
default:
throw new IllegalArgumentException("month not 1-12");
} // switch (too long for my liking)
and then
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
This utilizes a fall-through construct available in switches, so if you meet a condition, you are going to execute until a return statement (or break/throw).
Please remember that the alternative is to have something like:
private static final Set<Integer> MONTHS_30_DAYS = Sets.newTreeSet(4, 6, 8, 10, 12);
private static final Set<Integer> MONTHS_31_DAYS = Sets.newTreeSet(1, 3, 5, 7, 9, 11);
public static int numberOfDays(int month, int year) {
if (MONTHS_30_DAYS.contains(month)) {
return 30;
} else if (MONTHS_31_DAYS.contains(month)) {
return 31;
} else {
return (0 == year / 4) ? 29 : 28;
}
}
Here your day is dependent on the month entered. So firstly you'd want to take the month entered by the user as an Integer like you're doing now and proceed to use that number in a switch:
int month = 0;
int numberOfDays;
switch (month) {
case 1: numberOfDays = DaysInJanuary;
break;
case 2: numberOfDays = DaysInFebruary;
break;
case 3: numberOfDays = DaysInMarch;
break;
case 4: numberOfDays = DaysInApril;
break;
case 5: numberOfDays = DaysInMay;
break;
case 6: numberOfDays = DaysInJune;
break;
case 7: numberOfDays = DaysInJuly;
break;
case 8: numberOfDays = DaysInAugust;
break;
case 9: numberOfDays = DaysInSeptember;
break;
case 10: numberOfDays = DaysInOctober;
break;
case 11: numberOfDays = DaysInNovember;
break;
case 12: numberOfDays = DaysInDecember;
break;
default: throw new IllegalArgumentException("Not a valid month");
break;
}
You can then proceed to set your variable for the max day range.
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
Hope this helped.
Your day range depends on the previous month number the user entered, so you have to check that in order to know which day range to display. What the hint tells you is that you don't need a different range of valid days for each month because some months share the same range. Here are the number of days in a month:
January 31
February 28/29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
As you can see, there are only 3 groups and the assignment wants you to utilize fallthrough - when you don't break in a switch:
int upperDaysLimit;
switch(month) {
case 1:
case 3:
case 5:
//...
case 12: upperDaysLimit = 31;
break;
case 4:
case 6:
// and so on
}
and now you can use that range limit on your days inquiry:
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, upperDaysLimit);
If you're required to use switch statement, you can split months by the number of days in them. There will be 3 groups. Than you can use a switch statement as follows:
switch (month) {
case 1:
case 3:
case 5:
return 31;
case 2: {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
return 29;
else
return 28;
}
case 4:
case 6:
return 30;
default:
throw new IllegalArgumentException("some error text");
}
The switch statement in the example is not full, you should write a case statements for every month. Basically you're returning the upper value for day.

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

Okay, so my code is compiled but the if/else statement is not working

I think it might be due the switch statement.
Do I have make the both them switch statements for them to work out.
import java.util.Scanner;
public class mylab
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int month;
int day;
String season= "seasons";
System.out.print("type a two digit month");
System.out.print(" and day");
month = in.nextInt();
day = in.nextInt();
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
switch (month) {
case 1:
month = 1; System.out.println(" Winter");
break;
case 2:
month = 2; System.out.println(" Winter");
break;
case 3:
month= 3;System.out.println(" Winter");
break;
case 4:
month= 4;System.out.println(" Spring");
break;
case 5:
month = 5;System.out.println(" Spring");
break;
case 6:
month = 6 ;System.out.println(" Spring");
break;
case 7:
month = 7 ;System.out.println(" Summer");
break;
case 8:
month = 8;System.out.println(" Summer");
break;
case 9:
month = 9;System.out.println(" Summer");
break;
case 10:
month = 10;System.out.println(" Fall");
break;
case 11:
month = 11;System.out.println(" Fall");
break;
case 12:
month = 12;System.out.println(" Fall");
break;
}
How , do I make this part work with the switch statement
the pseudo code for this portion is If month is divisible by 3 and day >= 21, If season is "Winter", season = "Spring",Else if season is "Spring", season = "Summer",Else if season is "Summer", season = "Fall"
Else season = "Winter"
if (month % 3 == 0 && day >= 21)
{
if ( season.equals(winter) )
System.out.println(" Spring");
else if ( season.equals(spring) )
System.out.println ( "Summer" );
else if ( season.equals(summer) )
System.out.println ( " fall");
else if ( season.equals(winter) )
System.out.println( " winter");
}
}
}
This is how I'd probably write it (if I absolutely had to keep the switch and I didn't care to check user input):
import java.util.Scanner;
public class mylab {
public static void main(String[] args) {
int month, day;
Scanner in = new Scanner(System.in);
System.out.print("Type a two digit month: ");
month = in.nextInt();
System.out.print("Type a two digit day: ");
day = in.nextInt();
System.out.print(" Month="+ month +" Day= "+day+" ");
if(month%3==0 && day>=21) {
month++;
if(month>12) month=1;
}
switch (month) {
case 1: case 2: case 3: System.out.println("Winter"); break;
case 4: case 5: case 6: System.out.println("Spring"); break;
case 7: case 8: case 9: System.out.println("Summer"); break;
case 10: case 11: case 12: System.out.println("Fall"); break;
}
}
}

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