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

标签 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.");
                                }
                    }
                }
            }                   


        }               
    }
}

最佳答案

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

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提供的Date Class

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

关于java - 日期输入验证 - 修复 java.lang.numberformatexception 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39738001/

相关文章:

Java通过命令行从文件读取字符串作为 float 输入

java - 执行空检查而不引发 NullPointerException 的最佳方法是什么?

java - @FormParameter在ContainerRequestContext实体流中读取并设置相同数据后数据变为null

Javascript:在插入 Google 表格之前按月而不是按天对 csv 数据进行分组

php - 如何从mysql数据库中获取只有这一年的数据

python - RuntimeError : Expected all tensors to be on the same device, 但在恢复训练时发现至少两个设备,cuda :0 and cpu!

java - 如何创建具有特定最大实例数的 spring bean

java - 使用Spring Cloud Gateway时如何处理404错误

mysql - 在两个日期未格式化的日期之间进行选择

OpenCV::solvePNP() - 断言失败