验证日期输入 - 修复java.lang.numberformatexception错误

时间:2016-09-28 04:22:03

标签: java date runtime-error

我被要求制作一个程序,该程序将用户输入日期并检查几个标准:日期长度,闰年,月份准确度,日准确度等等...我相信我已经弄明白了除了当我测试日期" 12/345/678"我得到一系列Java错误,包括:

Exception in thread "main" java.lang.NumberFormatException: For input string: "/678"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at DateChecker.main(DateChecker.java:42)

我相信这是因为当java试图提取" yearString"它无法使用,因为它已使用intparser转换为整数,输入的代码现在包含" /"所以日期" 1 / 234/5678"会发生同样的错误。因为monthString正在查找所有整数,但它现在包含一个" /"。

我知道下面的代码,因为我已经阅读了另一篇类似问题的StackOverflow帖子,虽然当我尝试将此应用到我的程序时,我遇到了一系列编译器错误,因为我的变量现在已经关闭了该计划

try{
   int i = Integer.parseInt(input);
}catch(NumberFormatException ex){ // handle your exception
   ...
}

这是我到目前为止的代码,并提前感谢所提供的任何帮助:)

import java.util.*;

public class DateChecker {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in); //activates the keyboard

        String dateString; //variable declaration

        System.out.println("Please enter a date in the format (mm/dd/yyyy): "); //prints to screen
        dateString = keyboard.nextLine();//user enters dateString value

        if (dateString.length()>10)//checks if date is greater than 10
        {
            System.out.println("Invalid date."); //prints to screen
            System.out.println("To many characters in the date.");//prints to screen
        } 
        else if(dateString.length()<10)//checks if date is less than 10
        {
            System.out.println("Invalid date.");//prints to screen
            System.out.println("To few characters in the date.");//prints to screen
        }
        else {//date = 10
            if(dateString.charAt(2)!='/' && dateString.charAt(5)!='/')//checks for "/" at spots 2 and 5
            {
                System.out.println("Invalid date.");//prints to screen
                System.out.println("Incorrect format.");//prints to screen
            }
            else{//"/" at spots 2 and 5
                //declares variables and extracts strings
                String yearString = dateString.substring(6, 10);
                String dayString = dateString.substring(3, 5);
                String monthString = dateString.substring(0, 2);

                //converts string variables to integer
                int monthInt=Integer.parseInt(monthString);
                int dayInt=Integer.parseInt(dayString);
                int yearInt=Integer.parseInt(yearString);

                if(monthInt < 1|| monthInt > 12)//checks if valid month is entered
                {
                    System.out.println("Invalid date.");//prints to screen
                    System.out.println("Month is not valid.");//prints to screen
                }
                else
                {//month is valid
                    if(dayInt < 1)
                    {
                        System.out.println("Invalid date.");
                        System.out.println("Day is not valid.");
                    }

                    else {
                        if((monthInt == 4 || monthInt == 6 || monthInt == 9 || monthInt == 11) && dayInt > 30)//checks if months should have 30 days
                        {
                            System.out.println("Invalid date.");//prints to screen
                            System.out.println("Day is not valid.");//prints to screen
                        }
                        else
                            if (yearInt % 4 ==0 && (monthInt == 2 && dayInt > 29))//checks if leap year
                            {
                                System.out.println("Invalid date.");//prints to screen
                                System.out.println("Day is not valid.");//prints to screen
                            }

                            else//if not leap year
                                if (yearInt % 4 != 0 && dayInt > 28)//checks if normal year
                                {
                                    System.out.println("Invalid date.");//prints to screen
                                    System.out.println("Day is not valid.");//prints to screen
                                }

                                else //date entered was valid
                                {
                                    System.out.println("Valid date.");
                                }
                    }
                }
            }                   


        }               
    }
}

3 个答案:

答案 0 :(得分:1)

你可能应该使用像DateTimeFormatter.parse(CharSequence)这样的例子就是你的闰年规则是不正确的。如果年份可以被100整除,那么它不是闰年,即使年份可以被4整除,除非它也可以被400整除。在这种情况下它是闰年。

在你进入时区之前,日期很难......

答案 1 :(得分:1)

在你的代码中,问题出在这里: -

if(dateString.charAt(2)!='/' && dateString.charAt(5)!='/') //checks for "/" at spots 2 and 5 
{ 
    System.out.println("Invalid date.");//prints to screen
    System.out.println("Incorrect format.");//prints to screen 
}

在这里你要找到两个条件都是真的而不是你应该使用 OR 代替 AND

这是您需要做的一个小改动: -

if(dateString.charAt(2)!='/' || dateString.charAt(5)!='/') //checks for "/" at spots 2 and 5 
{ 
    System.out.println("Invalid date.");//prints to screen
    System.out.println("Incorrect format.");//prints to screen 
}

我建议你使用JAVA提供的日期类

谢谢你, 很乐意提供帮助:)

答案 2 :(得分:0)

如何使用已存在的类

System.out.println("Please enter a date in the format (mm/dd/yyyy): "); //prints to screen
String dateString = keyboard.nextLine();//user enters dateString value

SimpleDateFormat sdf = new SimpleDateFormat ("MM/dd/yyyy");

try {
   sdf.parse (dateString);
} catch (ParseException ex) {
    System.out.println("Invalid date.");//prints to screen
}