从用户获取日期(mm / dd / yyyy),检查是否有效,打印日期(月,日)

时间:2014-01-31 05:31:13

标签: java

我在做一些事情上遇到了困难。我是Java的新手,由于八进制数字,我无法弄清楚如何读取前两位数来确定08或09。此外,我得到一个返回null,1,199,不需要在那里。帮助将不胜感激。

import java.util.*;
public class Dates {

    public static void main(String[] args) {

        String January,February, March, April, May, June, July, 
        August, September,October, November, December, month;

        January = February = March = April = May = June = July = 
                August = September = October = November = December = month = null;


        Scanner myScanner = new Scanner(System.in); 
        System.out.print("Enter date in the format mm/dd/yyyy: ");

        String input = myScanner.next();

        String months = input.substring(0,1);
        int monthInt = Integer.parseInt(months);

        if (monthInt == 01){
            month = January;
        }
        else if (monthInt == 02){
            month = February;
        }
        else if (monthInt == 03){
            month = March;
        }
        else if (monthInt == 04){
            month = April;
        }
        else if (monthInt == 05){
            month = May;
        }
        else if (monthInt == 06){
            month = June;
        }
        else if (monthInt == 07){
            month = July;
        }
        else if (monthDouble == 08){
            month = August;
        }
        else if (monthDouble == 09){
            month = September;
        }
        else if (monthInt == 10){
            month = October;
        }
        else if (monthInt == 11){
            month = November;
        }
        else if (monthInt == 12){
            month = December;
        }
        else {
            System.out.println("Invalid Month");
        }

        String days = input.substring(3,4);
        int daysInt = Integer.parseInt(days);

        if ((daysInt <= 31) && (monthInt == 1 || monthInt == 3 || monthInt ==
                5 || monthInt == 7 || monthInt == 8 || monthInt == 10 || monthInt
                == 12)){
            daysInt = daysInt;
        }
        else if ((daysInt <= 30) && (monthInt == 4 || monthInt == 6 || monthInt
                == 9 || monthInt == 11)){
            daysInt = daysInt;
        }
        else if ((daysInt <= 28) && (monthInt == 2)){
            daysInt = daysInt;
        }
        else
            System.out.println("Invalid Day");

        String year = input.substring(6,9);
        int yearInt = Integer.parseInt(year);

        if (yearInt >= 1900 && yearInt <= 2014) {
            yearInt = yearInt;
        }
        else {
            System.out.println("Year should be between 1900 and 2014");
        }

        String checkSlash = input.substring(2);
        char slash = checkSlash.charAt(0);

        if (slash == '/')
            slash = slash;
        else
            System.out.println("Invalid format. Use mm/dd/yyyy");

        System.out.println(month + " " + daysInt + ", " + year);

    }
}

4 个答案:

答案 0 :(得分:4)

有更好的方法可以做到这一点,最明显的是使用Java的DateSimpleDateFormat类,但是如果你必须知道......

不要在整数上包含前导零。你不会是reading or otherwise dealing with八进制值。 1月是第一个月,将其表示为1更为直接。

如果你真的不想使用SimpleDateFormat,我会给你一个替代方案。考虑到我们知道所有值都落在一个整数范围内(也就是说,它们都将小于21亿)。如果我们让Integer类为我们解析值,那么我们可以用更少的代码来完成。

除此之外,我们不需要担心奇怪的子串(顺便说一句,你的只会抓住第一个元素 - 这是有问题的。)

让我们使用String#split()方法并在正斜杠上分解输入字符串。

String[] brokenInput = input.split("/");

现在,根据我们的格式和惯例,我们会看到月份位于brokenInput[0]brokenInput[1]中的日期和brokenInput[2]中的年份。

解析很容易:

Integer monthInt = Integer.parseInt(brokenInput[0]);
Integer daysInt = Integer.parseInt(brokenInput[1]);
Integer yearInt = Integer.parseInt(brokenInput[2]);

答案 1 :(得分:2)

尝试更简单的方法

String strDate = "11/29/2009";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date dateStr = formatter.parse(strDate);

答案 2 :(得分:1)

Java会将前导零的数字视为 octals ,八进制数中的数字不能大于7.如果您尝试使用08,{{{ 1}}。您可以改为使用09

String

我认为(因为你要与“01”,“02”,...)进行比较,你应该使用if (months.equals("01")) ...

substring(0,2)

答案 3 :(得分:0)

我会假设你有很长的路要走。

首先,在检查月份时删除0值的前导int,他们会将值转换为八进制,这是您不需要的...

if (monthInt == 1) {
    month = January;
} else if (monthInt == 2) {
    month = February;
} else if (monthInt == 3) {
    month = March;
} else if (monthInt == 4) {
    month = April;
} else if (monthInt == 5) {
    month = May;
} else if (monthInt == 6) {
    month = June;
} else if (monthInt == 7) {
    month = July;
} else if (monthInt == 8) {
    month = August;
} else if (monthInt == 9) {
    month = September;
} else if (monthInt == 10) {
    month = October;
} else if (monthInt == 11) {
    month = November;
} else if (monthInt == 12) {
    month = December;
} else {
    System.out.println("Invalid Month");
}

此...

String months = input.substring(0, 1);

将获得输入的第一个字符,但您已向用户询问mm/dd/yyyy,这表示您想要一个月和日的两位数值...此外,如果他们输入会发生什么在12

相反,您可以使用String[] parts = input.split("/");input分隔符上拆分String /,这(如果输入有效)将为您提供三个元素,每个元素各一个部分日期值。

然后你可以使用......

int monthInt = Integer.parseInt(parts[0]);
//...
int daysInt = Integer.parseInt(parts[1]);
//...
int yearInt = Integer.parseInt(parts[2]);

转换单个元素。

这就提出了一个问题,即在尝试拆分之前,你应该以一种有意义的方式验证输入值。

月份值均为null

String January, February, March, April, May, June, July,
       August, September, October, November, December, month;

January = February = March = April = May = June = July
        = August = September = October = November = December = month = null;

这基本上意味着您的输出始终以null开头。你实际上需要为这些分配一些有意义的价值。

我也会嘲笑其他人所说的话,除非你有充分的理由不这样做,我会用Calendar和某种DateFormat来做这一切。 ..

更新了(略高于顶部)示例

这基本上理解了您的想法并使用SimpleDateFormatCalendar来执行输入的实际检查,例如......

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Dates {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Date (mm/dd/yyyy):");
        String input = kb.nextLine();
        // This is a little excessive, but does a pre-check of the basic
        // format of the date.  It checks for a strict adhereance to
        // the nn/nn/nnnn format.  This might not be required as 
        // SimpleDateFormat can actually be configured to be lient in it's
        // parsing of values
        if (input.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
            try {
                // Parse the String input to a Date object
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                Date date = sdf.parse(input);
                // Create a Calendar, going to use this to compare the resulting
                // Date value, as the parser will auto correct the input
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);

                // Split the basic input along the / delimeter
                String parts[] = input.split("/");
                boolean valid = true;
                // Check each part to make sure it matches the components of the date
                if (Integer.parseInt(parts[0]) != cal.get(Calendar.MONTH) + 1) {
                    valid = false;
                    System.out.println(parts[0] + " is not a valid month");
                } 
                if (Integer.parseInt(parts[1]) != cal.get(Calendar.DATE)) {
                    valid = false;
                    System.out.println(parts[1] + " is not a valid day of the month");
                } 
                if (Integer.parseInt(parts[2]) != cal.get(Calendar.YEAR)) {
                    valid = false;
                    System.out.println(parts[2] + " is not a valid year");
                }

                if (valid) {
                    // Print the result...
                    System.out.println(new SimpleDateFormat("MMMM dd, yyyy").format(date));
                }
            } catch (ParseException ex) {
                System.out.println("Unable to parse " + input + "; invalid format");
            }
        } else {
            System.out.println("Invalid format");
        }
    }

}