Write a Java program to find the number of days in a month


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class JavaExcercise {
  3.  
  4.  
  5. public static void main(String[] strings) {
  6.  
  7. Scanner input = new Scanner(System.in);
  8.  
  9. int numberOfDaysInMonth = 0;
  10. String MonthName = "Unknown";
  11.  
  12. System.out.print("Input a month number: ");
  13. int month = input.nextInt();
  14.  
  15. System.out.print("Input a year: ");
  16. int year = input.nextInt();
  17.  
  18. switch (month) {
  19. case 1:
  20. MonthName = "January";
  21. numberOfDaysInMonth = 31;
  22. break;
  23. case 2:
  24. MonthName = "February";
  25. if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
  26. numberOfDaysInMonth = 29;
  27. } else {
  28. numberOfDaysInMonth = 28;
  29. }
  30. break;
  31. case 3:
  32. MonthName = "March";
  33. numberOfDaysInMonth = 31;
  34. break;
  35. case 4:
  36. MonthName = "April";
  37. numberOfDaysInMonth = 30;
  38. break;
  39. case 5:
  40. MonthName = "May";
  41. numberOfDaysInMonth = 31;
  42. break;
  43. case 6:
  44. MonthName = "June";
  45. numberOfDaysInMonth = 30;
  46. break;
  47. case 7:
  48. MonthName = "July";
  49. numberOfDaysInMonth = 31;
  50. break;
  51. case 8:
  52. MonthName = "August";
  53. numberOfDaysInMonth = 31;
  54. break;
  55. case 9:
  56. MonthName = "September";
  57. numberOfDaysInMonth = 30;
  58. break;
  59. case 10:
  60. MonthName = "October";
  61. numberOfDaysInMonth = 31;
  62. break;
  63. case 11:
  64. MonthName = "November";
  65. numberOfDaysInMonth = 30;
  66. break;
  67. case 12:
  68. MonthName = "December";
  69. numberOfDaysInMonth = 31;
  70. }
  71. System.out.print(MonthName + " " + year + " has " + numberOfDaysInMonth + " days\n");
  72. }
  73. }

Result

java techstudy.org

     





Related Topics




Popular Posts