I am confused about how to do this in Java

I need help with an assignment. Here it is:

  1. Write a program that prompts the user to enter a month (1–12) and year, then displays the number of days in the month. For example, if the user entered month 2 and year 2012, the program would display that February 2012 has 29 days. Be careful with February. If the year entered is a leap year, your output should show that February has 29 days. Use the “Case Study: Determining Leap Year” on p. 105 of Introduction to Java Programming for information on how to calculate the leap year. It does not exactly happen every four years.

This is my code:

import java.util.Scanner;
public class MonthandYear {
public static void main(String[] args) {
//Create a Scanner
Scanner input=new Scanner(System.in); 
//Prompt the user to enter a year
System.out.print("Enter a year: "); 
int year=input.nextInt(); 
//Prompt the user to enter a month
System.out.print("Enter a month, name only: "); 
int month=input.nextInt(); 
if month="January" {
    System.out.print("This month has 31 days"); 
    }
    if month="Febuary" {
        System.out.print("This year, this month has" + number of days); 
    }
    }
}

How do I do this? I am getting confused, but I am trying to understand the basics so I can do this assignment by tomorrow night. Please help as soon as you can

First of all, read the directions carefully. You’re going to lose points because you’re not doing something correctly (hint - reread how everything is supposed to be entered)

Then I would do it this way

  1. Check if Month is February. If so, follow the pattern described on p. 105 to calculate the number of days - basic math is if year is divisible by four, it’s a leap year (29 days), otherwise it’s not (28). There are exceptions though.
  2. If month is NOT February, you need to determine if it’s a month with 30 or 31 days. HINT: Use the old nursery rhyme (30 days hath…). You could use a bunch or it statements or use another method (have you learned about case statements or arrays yet?).
  3. Once you’ve calculated the appropriate number of days, THEN display it.

Thanks for the tip. No, I have not learned it yet. I only really learned if/else statements, and I think that it may play into a huge part in this. I also know that I am going to need to create a Scanner. That’s about all I know. This is my second assignment, and I am on my 6th Unit, so not a whole lot of practice, but yea, thanks for the tip, @DaveMaxwell !

OK, then if you’re limited to if/else, the basic concept will be (sorry, syntax may not be right, it’s been a LOOOOOOOONG time since I’ve done Java)

// do input logic here

// initialize your variable, but assume it's for 31 days unless one of the exceptions...
int numDays = 31;
if (month == 2) {
   // February - get logic from p.105
} else if (month == 4 || month == 6 || month == 9 || month == 10)    {
   numDays = 30;
}
 
// Display results out
System.out.print("This year, this month has " + numDays);

All right, I am here, and this is what I have for it:

import java.util.Scanner;

public class MonthandYear {
public static void main(String[] args) {
//Create a Scanner
Scanner input=new Scanner(System.in); 
//Prompt the user to enter a month
System.out.print("Enter a month, numbers only: "); 
//Prompt the user to enter a year
System.out.print("Enter a year: "); 
int numDays = 31;
if (month == 2) {
   // February - get logic from p.105
} else if (month == 4 || month == 6 || month == 9 || month == 10)    {
   numDays = 30;
}
 
// Display results out
System.out.print("This year, this month has " + numDays);
}
}

You said that I needed to get logic on pg. 31. What are you talking about here? This code is not working, mostly because I know I don’t have everything that I need, but I am still not sure where to get this information

Remember when I said to read the directions clearly? I’ll say it again.

From your original post - it’s in your book.

 Be careful with February. If the year entered is a leap year, your output should show that February has 29 days. Use the “Case Study: Determining Leap Year” on p. 105 of Introduction to Java Programming for information on how to calculate the leap year. It does not exactly happen every four years.

I don’t mean to sound brutal, you’re not going to survive this class (or any programming class) by copy/pasting without taking a minute to figure out what is happening and why. I find the easiest way to think about it is to start to work these like math problems. What is the end goal to be achieved? What steps are needed to get there. Remember the old adage of “show your work?” - yeah, still applies.

The reason I say this is if you put your code into a compiler, it told you exactly what you were doing wrong. You dropped the lines that did the actual input, so the code won’t compile.

I’m going to be nice and provide you a partial solution. This works EXCEPT for the fact that February is wrong/incomplete because I don’t have access to the book that you do… This brings back the appropriate count for most months, but February is just 28 because I don’t have time to do that math.

import java.util.Scanner;

public class MonthandYear {
    public static void main(String[] args) {
        //Create a Scanner
        Scanner input=new Scanner(System.in); 
        
        //Prompt the user to enter a month
        System.out.print("Enter a month, numbers only: "); 
        int month=input.nextInt(); 
        
        //Prompt the user to enter a year
        System.out.print("Enter a year: "); 
        int year=input.nextInt(); 
        
        // Calculate the number of days in the month based on the values entered.
        int numDays = 31;
        if (month == 2) {
            // February - get logic from p.105
            numDays = 28;
        } else if (month == 4 || month == 6 || month == 9 || month == 10)    {
            numDays = 30;
        }
 
        // Display results out
        System.out.print("This year, this month has " + numDays);
    }
}

I understand what you are saying here. Thanks for the help you are providing here. @DaveMaxwell The only reason why I am asking for help, cause I see no sequence in this type of programming. I took a little bit of HTML and CSS(Not sure if you really call that coding), but I understood it because I saw the sequence. Copying and pasting is not all I want to do. I like programming, but yeah, I see no sequence in Java. So how do I know what to do when I run into a problem like this again. I do not mean to take all the codes from you, so I would like to know what to do in what order. My younger brother is taking the same class, and I would like to help him if I really need too. Any tips? Again, I am sorry for doing all of this to you. I understand that I may be a bit frustrating, but I really am thankful for everything that you have done for me so far

Programming is all about identifying patterns. What needs to be accomplished? What tools can be used to accomplish this?

What is the answer needed? Given a month and year, how many days are in that month?
How do we get that answer?

  1. Prompt user to enter the month
  2. Prompt user to enter the year
  3. Using the month and year, calculate the number of days.

Then you need some tools to do this

  1. A way to display prompts/messages to the user (Scanner)
  2. A way to get inputs (System.out.print)

So if we apply it to the code block

import java.util.Scanner;

public class MonthandYear {
    public static void main(String[] args) {

        // Create a Scanner - needed to get inputs from a console.
        Scanner input=new Scanner(System.in); 
        
        // Step 1
        // Prompt the user to enter a month and accept that input into a variable
        System.out.print("Enter a month, numbers only: "); 
        int month=input.nextInt(); 
        
        // Step 2
        // Prompt the user to enter a year and accept that input into a variable
        System.out.print("Enter a year: "); 
        int year=input.nextInt(); 
        
        // Step 3
        // Using the entered month and year, calculate the number of days in the month

         // MOST months have 31, so default to that and allow for modifications based on month
        int numDays = 31;
        if (month == 2) {
            // February - get logic from p.105
            numDays = 28;
        } else if (month == 4 || month == 6 || month == 9 || month == 10)    {
            numDays = 30;
        }
 
        // Display results out
        System.out.print("This year, this month has " + numDays);
    }
}

Now, to add complexity to this, you should be doing some error checking as well (ensuring the month and year are numeric, and that month has a value between 1-12) but I’m guessing that falls outside the scope of the assignment as well.

And I know the point of this exercise is to teach you the fundamentals, but giving you an exercise which has a built in java solution seems a bit…silly

Using built in Java functionality
import java.util.Scanner;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class MonthandYear {
    public static void main(String[] args) {
        //Create a Scanner
        Scanner input=new Scanner(System.in); 
        
        //Prompt the user to enter a month
        System.out.print("Enter a month, numbers only: "); 
        int month=input.nextInt(); 
        
        //Prompt the user to enter a year
        System.out.print("Enter a year: "); 
        int year=input.nextInt(); 
        
        // Create a calendar object and set year and month
        Calendar mycal = new GregorianCalendar(year, (month - 1), 1);
        // Get the number of days in that month
        int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
        // Display results out
        System.out.print("Number of days in " + month + "/" + year + " is " + daysInMonth);
    }
}
1 Like

40 years or so ago on my first programming course we were required to draw a flow chart before we got down to marking the cards.
Believe it or not this was one of the exercises in that course.
Using if/else is exactly how flow charts work.
And then doing a truth table shows whether the flow chart logic(the algorithm) is correct.
I still draw flow charts when I encounter a problem.

So Java is almost like proving something in Geometry, like A is congruent to B, and you need to prove it by using all of those postulates or theorems. Do you think that doing something like this for the if/else statements might be good for me to do? The image below is just for fun.

Kiiiiiinda…but not really.

In mathematical terms, programming more closely equates to a word problem than a specific approach.

  • Define the problem
  • What information is needed to solve the problem?
  • What steps are needed to get from the initial factors to the solution.

An IF/ELSE is a form of decision making. To use your for fun image,

  • IF you get a dog, expect to be loved constantly
  • ELSE IF you get a cat, expect to be ignored and treated with disdain
  • ELSE have more money because dogs and cats are expensive!
1 Like

Thanks for that. Here's and example, just so I know what you are saying is correct:

  • IF you go to the doctor, you are to pay a bill
  • ELSE IF you don't go to the doctor, you will expect no bill
  • ELSE have a good paying job, earn lots of money, cause they are expensive

I can see the what you mean by defining the problem. Look at what you need to do. I need to search what I need to do the code, then do the steps, if I am correct. Now, here's another question: How do I know what to do in what order?

Not really because the results of your ELSE IF and ELSE are pretty much the same. To carry your analogy to use an IF, ELSE IF, ELSE scenario, it would be more like…

  • IF you go to a doctor that accepts your insurance, you will get a bill but should get better
  • ELSE IF you go to a doctor that DOESN’T accept your insurance, you will get a much larger bill but should get better
  • ELSE you won’t have any bills but probably won’t get better since you didn’t go to the doctor.

You have to think logically and break it down. If you know the end goal, work your way backwards

In your case:

  1. Problem: A user wants to know how many days are in a particular month in a year
  2. What do we need to know first?
    • How many days are in each month
    • What month and year is the user looking for?
  3. Solution, use the month and year to calculate the correct number of days
    1. Is the month February? If so, check the year to determine if it’s 29 or 28
    2. Is the month one of the 30 days months? If so, there must be 30 days
    3. There must be 31 days if 3.1 and 3.2 are both false

If you can’t figure out 1 & 2 clearly, you’re never going to be able to do 3 and find the solution. For example. If you were given only the month in your problem, you could never guarantee that you could give the correct answer because of February because of a leap year.

Then the trick comes down to solving the problem the easy way or the hard way.

You could calculate whether it’s a leap year each time, but it doesn’t matter unless you’re asking about February.

Or you could have a list of each month and go from there

if month = 1 {
   numDays = 31
} else if month = 2 {
   numDays = 28 or 29
} else if month = 3 {
   numDays = 31
} else if month = 4 {
   numDays = 30
} else if month = 5 {
   numDays = 31
} else if month = 6 {
   numDays = 30
} else if month = 7 {
   numDays = 31
} else if month = 8 {
   numDays = 31
} else if month = 9 {
   numDays = 30
} else if month = 10 {
   numDays = 31
} else if month = 11 {
   numDays = 30
} else if month = 12 {
   numDays = 31
} 

Or you can use logic and use process of elimination

if month = 2 {
   numDays = 28 or 29
} else if month = 4 or 6 or 9 or 11 {
   numDays = 30
} else {
   numDays = 31
}

Just a note that what @DaveMaxwell is using here is known as pseudo-code. It’s high-level, won’t compile in any language, but lays out the principles for communication to other developers. Most developers can understand what is meant, regardless of which language they program in.

1 Like

For that last post, he’s right. I was more concerned about getting the concept across than making it java correct - the working post from earlier is syntactically correct.

1 Like

I got you guys. Thanks for the help. Hope you both have a great day, and happy programming!

1 Like

Hi. I am back with this subject again. So here is my current code for this thing(does not involve calendar usage):
package Lesson;

import java.util.Scanner;

public class MonthandYear {

	public static void main(String[] args){
		Scanner input=new Scanner(System.in);
		//Prompt the user to enter a month	
		System.out.println("Enter a month, 1-12: ");
		int month=input.nextInt();
		if (month > 12) {
			System.out.println( month + " is not a valid month. Please enter a valid month");
			main(args);
		}
		else if (month < 1) {
			System.out.println( month + " is not a valid month. Please enter a valid month");
			main(args);
		}
		else {
		}
		//Prompt the user to enter a year
		System.out.println("Enter a year: ");
		int year=input.nextInt();
		
		//Check to see if leap year
		boolean leapYear = false;
		String isLeapYear;
		if (year % 4==0 && year % 100 !=0 || (year % 400 == 0)) {
			leapYear = true;
			isLeapYear="Yes, it is a leap year.";
			}
		
		else {
			isLeapYear="No, it is not a leap year.";
					
		}
		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:


//		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		if (leapYear = true) 	
			numDays = 29;
			else if (leapYear = false)
			numDays = 28;
			break;


		}
		

		
		//Display the results
		System.out.println("There are " + numDays + " days in " + month + "/" + year + ". Is this a leap year? " + isLeapYear);
}
}

I run this thing to test the year of 1900, as it was not a leap year, and I expected it to come out. This is what I get instead:

I know that there there is only 28 days in 1900 for February, sooo… where am I getting this wrong? I can really only use what I have in my code, but I don’t see the mistake. Teacher wants me to use this. Rub this code yourself for all I care. just about everything works, except for February. 2022 is showing the exact same thing. Where is my error?

From Wikipedia:

These extra days occur in each year which is an integer multiple of 4 (except for years evenly divisible by 100, but not by 400)

(https://en.wikipedia.org/wiki/Leap_year)

That is not what this does:

if (year % 4==0 && year % 100 !=0 || (year % 400 == 0)) {

and that’s where it’s going wrong.

@rpkamp you forgot to close parenthesis ( I tried to bold parenthesis you have ommited, but forgot this is markdown so unfinished piece of crap that wont let me nest syntax )

if ((year % 4==0) && (year % 100 !=0) || (year % 400 == 0)) {
 // Code here.......
}

The answer is simpler than that. The problem is with this line…

		if (leapYear = true) 	

That is assigning a value to the variable. If you want to do a comparison, you need to use two equal signs.

And not to be pedantic, but a boolean can only ever be true or false, so the extra if statement is not needed.

		if (leapYear == true) 	
			numDays = 29;
		else
			numDays = 28;
		break;

But you also don’t need the boolean at all.

		case 2:
  			if (year % 4==0 && year % 100 !=0 || (year % 400 == 0)) {
				numDays = 29;
				isLeapYear="Yes, it is a leap year.";
			}
			else {
				numDays = 28;
				isLeapYear="No, it is not a leap year.";
			}
			break;