Hello! I need help with programming. I'm supposed to create a program that will ask you for a year and a month (year: 2011, Month: 1 for January, 2 for February, etc) and it will tell you how many days are in that month (including leapyears). This is what i have so far:
import java.util.Scanner; public class Welcome { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter a year:"); int year = input.nextInt(); System.out.print("Enter a month:"); int month = input.nextInt(); 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; } } }
whats the problem?
The switch statement might require a default? I'll test it.
When I try to run the program, it wont tell me the days. It'll ask for the year, and then the month, but then the program terminates. I also need a failure message, so if you type '99' for the year it'll tell you that its 99 is not a year.
nvm switch doesn't require a default.
The variable days is indeed being set to a value when you run it- however, you never display it's value.
well thats a bit more advanced than what you are doing
woodrow will help you
Never displayed its value? Hmm I thought the case _ : days = __ was its value?
Obviously I'm wrong then.. I'm very lost.. Java programming turned out to be a lot harder then I had initially assumed
You're statement is actually correct.. think of java programming (I believe most languages to be the same way) are read in a top-down format. So after the user inputs a year and month -- the int value days is assigned the proper value. However, just because days holds a value, doesn't mean that it is displayed. To display any variable in java -- you use this magic line of code: ``` System.out.println("this is what the program will print. Hello from java"); ``` If you are displaying a variable like 'days', then you simply put it in the parenthesis without using quotes- like so-- ``` System.out.println(days); ``` Though if you want text to be displayed, then you use quotations like so: ``` System.out.println("Hello world"); ``` If you want it to print a combination of text and variables, you use the + symbol to combine them like so: ``` System.out.println("There are " + days + " days in the month " + month + "."); ```
Alright thank you!
No problem :). If you know where to get this type of information, java syntax isn't too hard to learn.
Textbooks are probably one of the better resources -- like one giant tutorial.
Thank you again!
yw
Join our real-time social learning platform and learn together with your friends!