【问题标题】:Validating date from user input根据用户输入验证日期
【发布时间】:2016-02-26 03:35:27
【问题描述】:

我正在编写一个程序,我应该让用户输入一个从 0 年到 4000 年的日期。我应该看看日期是否有效,以及它是否是闰年。我的代码有问题。 我在第 57 行得到了一个没有错误的 else 。 我也不确定如何判断日期是否有效。 IE:此日期有效,是闰年 - 或无效不是闰年......等等......

我还是一个初学者,所以我不想为我编写代码,但我想知道如何修复它!谢谢你。

import java.util.*;

public class LegalDate   //file name
{
        public static void main (String [] args)

    {
        Scanner kb = new Scanner (System.in); //new scanner
        //name the variables
        int month, day, year;
        int daysinMonth;
        boolean month1, year1, day1;
        boolean validDate;
        boolean leapYear;



        //ask the user for input
        //I asked the MM/DD/YYYY in seperate lines to help me visually with the program
        System.out.println("Please enter the month, day, and year  in interger form: " );
        kb.nextInt();

        //now I'm checking to see if the month and years are valid
        if (month <1 || month >12)
            { month1 = true;}
        if (year <0 || year >4000)
            {year1= true;}

        //I'm using a switch here instead of an if-else statement, which can also be used


             switch (month) {
                case 1:
                case 3:
                case 5:             //months with 31 days
                case 7:
                case 8:
                case 10:
                case 12:
                     numDays = 31;
                     break;
                 case 4:
                 case 6:              //months with 30 days
                 case 9:
                 case 11:
                     numDays = 30;
                     break;

                 case 2:
                     if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))  //formula for leapyear
                         numDays = 29;
                            {
                                system.out.println("is a leap year");
                                }
                     else
                         numDays = 28;
                            {
                                system.out.println("is not a leap year");
                                }
                     break;
                default:
                     System.out.println("Invalid month.");
                break;

                     if (month1 == true)
                     if (day1 == true)
                     if (year1 == true)
                           System.out.println ("date is valid ");

                     else
                     if (month1 == false)
                           System.out.println ("date is invalid");

                     else
                     if (day1 == false)
                           System.out.println ("date is invalid");

                      else
                      if (year1 == false)
                           System.out.println ("date is invalid");



    }}

}

【问题讨论】:

    标签: java validation date switch-statement


    【解决方案1】:

    在第 57 行,您打开了一个新代码块,但没有任何东西可以访问它。我相信你的意思是输入:

    else{
            numDays = 28;
            system.out.println("is not a leap year");
        }
    

    作为一个小提示,您可以更改此设置:

    if (month1 == true)
                     if (day1 == true)
                     if (year1 == true)
                           System.out.println ("date is valid ");
    

    对此:

    if (month1 && day1 && year1)
       System.out.println ("date is valid ");
    

    由于布尔比较运算符返回真或假,您可以看出条件只需要为布尔值。由于month1day1year1 都是布尔值,因此您无需将它们与任何东西进行比较。

    如果您不知道,条件的含义是如果month1day1year1 都为真,则打印date is valid

    【讨论】:

      【解决方案2】:

      你为什么不试试 Java 8 日期时间 API

      它会验证日期并为您做更多事情

      喜欢

      try {
              LocalDate date =LocalDate.of(2016, 12, 31);
              if(date.isLeapYear())
                  System.out.println("Leap year");
              else 
                  System.out.println("Not leap year"); 
      }
      catch(DateTimeException e) {
         System.out.println(e.getMessage());
      }
      

      【讨论】:

        【解决方案3】:

        您似乎没有将代码放在大括号中的“if”和“else”语句之间,这意味着该语句仅适用于下一行。例如:

        if (a)
            b = true
            c = true
        else
            d = true
        

        读作

        if (a) {
            b = true
        }
        c = true
        else {
            d = true
        }
        

        希望您能看到编译器无法理解这一点,因为“else”语句必须直接出现在其关联的“if”块之后。

        我建议添加一些方法来简化您的代码。例如:

        public static boolean isLeapYear(int year) {
            return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
        }
        

        另外,如果你使用布尔变量来存储信息,你可以在最后整齐地打印出来。例如,您可以在代码顶部将变量“isValid”实例化为 true,如果您计算出日期无效,则将其设置为 false,并在末尾使用 if 语句来打印结果。

        我知道您说过您不想为您编写它,但这是展示方法重要性的最简单方法。希望您能看到这比您的版本更具可读性吗?

        import java.util.Scanner;
        
        public class LegalDate {
        
            static final int maxYear = 4000;
        
            public static void main (String [] args) {
                int month, day, year;
                boolean leapYear, validDate = false;
        
                Scanner kb = new Scanner (System.in);
                System.out.println("Please enter the month, day, and year in interger form.");
        
                System.out.print("Month: ");
                month = kb.nextInt();
                System.out.print("Day: ");
                day = kb.nextInt();
                System.out.print("Year: ");
                year = kb.nextInt();
        
                leapYear = isLeapYear(year);
                validDate = isValidDate(month, day, year);
        
                System.out.printf("%nThe date is %svalid and is %sa leap year.%n", validDate ? "" : "not ", leapYear ? "" : "not ");
                kb.close();
            }
        
            public static int numDaysInMonth(int month, boolean isLeapYear) {
                switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                     return 31;
                case 4:
                case 6:
                case 9:
                case 11:
                     return 30;
                case 2:
                     if (isLeapYear) {
                         return 29;
                     } else {
                         return 28;
                     }
                default:
                     return 0;
                }
            }
        
            public static boolean isLeapYear(int year) {
                return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
            }
        
            public static boolean isValidDate(int month, int day, int year) {
                return (month >= 1 && month <= 12) && (day >= 1 && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= 0 && year <= maxYear);
            }
        }
        

        如果您有任何问题,我会尽力回答!

        【讨论】:

        • 谢谢!我知道我的代码很草率,但我没有意识到它有多么分散。感谢您的帮助!
        • 我确实有一个问题,在我的课程中我们还没有进入这部分' System.out.printf("%n日期是 %s 有效并且是 %sa 闰年。%n" , validDate ? "" : "not ",leapYear ? "" : "not ") kb.close(); '我一直试图找出它是什么,但你如何使用它?你用它来代替 if-else 语句吗?
        • printf 是一种用变量替换占位符(%s 表示字符串,%d 表示数字等)的方法,%n 是换行符。 condition ? execute_if_trueexecute_if_false 正如您所建议的,是 if/else 的简写。因此,如果日期无效,则在第一个 %s 中插入“not”,如果日期不是闰年,则在第二个 %s 中插入“not”(否则插入一个空字符串)。 kb.close() 只是释放与您的扫描仪关联的资源。这将在您结束程序时自动发生,但最好手动放入。
        【解决方案4】:

        你的程序第 50 行 if-else 语句的语法不正确。 这是一个悬而未决的东西。将 if 和 else 语句的主体括在大括号内应该可以解决这个问题。

        if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))  
        { 
            numDays = 29;                            
            system.out.println("is a leap year");
        }
        else
        {
            numDays = 28;
            system.out.println("is not a leap year");
        }
        

        您可以利用IDE或关注编译器错误信息来解决此类错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-15
          • 2018-06-28
          • 2018-05-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-15
          相关资源
          最近更新 更多