【问题标题】:Validating a Date Using Delimiters使用分隔符验证日期
【发布时间】:2018-04-23 07:54:41
【问题描述】:

我目前有验证输入日期的家庭作业。
该任务要求我:
• 说明输入日期无效以及无效的原因 例如3062 年 7 月 3 日 - 无效:年份超出范围。

• 以下列格式输出有效日期: 呸呸呸呸 例如 1882 年 4 月 1 日

我的老师想要格式日月年。

输入可以是以下任何一种格式:
日期:dd 或 d 或 0d
月份:mm 或 m 或 0m 或月份名称的前三个字母(全部相同,或首字母大写)
年份:yy 或 yyyy
分隔符:- 或 / 或
注意:一个日期只能使用一种分隔符类型

我见过很多需要以整数形式给出月份的示例,但我不确定如何将月份输入为“Jan”。任何见解都会非常有帮助。以下是我目前拥有的代码:

import java.util.*;
import java.io.*;

    public class Dates{
      public static void main(String[] args){
        //int minYear = 1753, maxYear = 3000;
        int day, month = 0, year = 0;
        int daysInMonth;
        boolean validDay, validMonth, validYear;
        boolean leapYear;

        Scanner sc = new Scanner(System.in); /*A file or user input?*/
        sc.useDelimiter("/|-|\n"); //how to separate space
        while(sc.hasNextLine()){
          String line = sc.nextLine(); //read line into a string
          //find the deliminator

    }

    //check day

    //check month
    leapYear = ((year % 4) == 0 && ((year % 100) != 0) || (year % 400) == 0);
    validMonth = (month >= 1 && month <= 12);

    //check year
    validYear = (year >= 1753 && year <= 3000);

  }
}

【问题讨论】:

    标签: java validation date


    【解决方案1】:

    您可以使用switch 处理String 输入,

    switch(month){
    case "Jan":
      return 1;
    case "Feb":
      return 2;
    ...
    case "Dec":
      return 12;
    default:
    //every other input can be handled here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多