用户输入日期在解析为 SimpeDateFormat 时出错

问题描述

我正在尝试输入用户的日期。但是代码在 parse 方法中给出了错误。我正在尝试的代码如下。

import java.util.*;
import java.text.SimpleDateFormat;

public class date_parse {
    public static void main(String args[]) {
        Scanner input=new Scanner(system.in);
        String s=input.nextLine();
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(f.parse(s));
    }   
}

注意 -:如果我直接在解析方法中的 os s 处提供字符串格式日期(如“01-01-2000”),则代码运行良好

解决方法

首先,您不会像在 Java 中那样命名您的类。请阅读 this 文章以了解有关 Java 中命名约定的更多信息。其次,正如 Risalat Zaman 提到的,parse 方法会抛出需要在您的代码中处理的 ParseException。尝试按如下方式更改您的代码:

public class DateParse {
    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        String s=input.nextLine();
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        try {
            System.out.println(f.parse(s));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
,

试试这个

    try{
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(f.parse(s));     
    }
    catch(Exception e){
        System.out.print("There is an exception");
    }