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.
Related
How do i take the user inputted day, month and year then store in a dd-mm-yyyy format? I can get everything to work except combining them into a date and storing them in the startDate variable. I also don't think startMonth will be accessible as it's in a switch case but I'm very new to java and unsure.
public static void carBookingDates() {
int carNumber;
int startYear;
int startDay;
int startMonth;
int daysInMonth = 0;
int endYear;
int endMonth;
int endDay;
Scanner input = new Scanner(System.in);
System.out.println("To make a booking:");
System.out.printf(" Select a car number from the car list: ");
carNumber = input.nextInt();
System.out.println("");
System.out.println("Enter a booking start date.");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
while (startYear < 2022 || startYear > 2030) {
System.out.println("Invalid year, please try again: ");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
}
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
while (startMonth < 1 || startMonth > 12) {
System.out.println("Invalid month, please try again: ");
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
}
switch (startMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
case 2:
if (((startYear % 4 == 0)
&& !(startYear % 100 == 0))
|| (startYear % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
while (startDay > daysInMonth || startDay <= 0) {
System.out.println("Invalid day, plese try again");
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
LocalDate startDate() = LocalDate.parse(startDay + "-" + StartMonth "-" + startYear);
}
}
First of all, you can use the Java 8 Date Time API to get the number of days in a month instead of using a manual switch case for making the code more readable.
import java.time.YearMonth;
Then:
// 2021 is the year and 2 is the month
int daysInMonth = YearMonth.of(2021,2).lengthOfMonth());
Now to form the date in dd-mm-yyyy format :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Then:
// pass your date value here under LocalDate.of method
LocalDate.of(2021,2,16).format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
I am making a program with alot of boolean true or false statement, I want the output of the boolean to be read by scanner and want it as some kind of output, Is there way to do it
Ex:
if (day == 1){System.out.print("first");}
if (month == 1){System.out.println("Your birthday is " + day + " January");}
pretty much I ask the user to input an number and it will convert it to the actual month's name and it will tell them their birthday by converting numbers, but when I do the way I am its just going to print it out. I want to make Scanner read the input 1 as first and want it to write as "Your birthday is first January"
You can use a switch statement and set your response string based on the number they entered and use that in your print statement.
String response;
switch(day){
case 1: response = "first";
break;
case 2: response = "second";
break;
/*
And so on...
*/
}
Try with this approach:
public static void main(String[] args) {
final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Scanner sc = new Scanner(System.in);
System.out.println("Type month: ");
int month = 0;
while(sc.hasNextInt()) {
month = sc.nextInt();
// get month from 1 to 12
if (month > 0 && month < 12) {
break;
} else {
System.out.println("Type valid month: ");
continue;
}
}
System.out.println("Type day: ");
while (sc.hasNextInt()) {
int day = sc.nextInt();
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31; break;
case 4:
case 6:
case 9:
case 11:
numDays = 30; break;
case 2: numDays = 28; break;
}
// get day taking under consideration amount of days in the month
if (day > 0 && day <= numDays) {
System.out.println("Your birthday is " + day + " " + months[month-1]);
return;
} else {
System.out.println("Type valid day: ");
continue;
}
}
}
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 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.
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?