therrontelford

Number of days in month

Nov 12th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. import java.util.Scanner;
  2. class Chapter3_11NumberOfDaysInMonth {
  3.  
  4.     public static void main(String[] args) {
  5.         Scanner kb = new Scanner(System.in);
  6.         System.out.println("Enter a month and year.  1 for Jan, 2 for Feb, etc");
  7.  
  8.         // get user input
  9.         int month = kb.nextInt();
  10.         int year = kb.nextInt();
  11.         int days = 0;   // I will need to know how many days, so I set this variable initially to 0.
  12.  
  13.         // use the isLeapYear we wrote to determine if the year is a leap year
  14.         boolean isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); // this will evalutate to true or fal
  15.          
  16.        
  17.         if ( month == 1 ||month==3||month==5||month==7||month==8||month==10||month==12 ){
  18.             days = 31;
  19.         }
  20.         else if (month==4||month==6||month==9||month==11){
  21.             days = 30;
  22.         }
  23.         else if (month == 2){
  24.             if (isLeapYear)
  25.                 days = 29;
  26.             else
  27.                 days=28;
  28.         }
  29.         // use a switch statement to get the name of the month.  It's a cleaner if, else if, way to go about it.
  30.         String name="";
  31.        
  32.         switch (month){
  33.         case 1: name = "January";break;
  34.         case 2: name = "February";break;
  35.         case 3: name = "March";break;
  36.         case 4: name = "April";break;
  37.         case 5: name = "May";break;
  38.         case 6: name = "June";break;
  39.         case 7: name = "July";break;
  40.         case 8: name = "August";break;
  41.         case 9: name = "September";break;
  42.         case 10: name = "October";break;
  43.         case 11: name = "November";break;
  44.         case 12: name = "December";break;
  45.         }
  46.        
  47.         System.out.println( name + " "+ year + " has "+ days + " days.");
  48.            
  49.         }
  50.  
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment