有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

分析线程“main”java中的异常。时间总体安排DateTimeParseException:未能在索引0处分析文本“”

我有一个扫描器,可以读取2个字符串,并将其更改为LocalDate,但它不计算扫描器的数量,并给了我这个错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)     .....................location of my classes

代码:`

String date1 = sc1.nextLine();
String date2 = sc1.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate dateDebut = LocalDate.parse(date1,formatter);

    System.out.println(dateDebut);
    a1.setDateDeb(dateDebut);

    System.out.println(dateFin);
    a1.setDateFin(dateFin);

但当我用字符串日期(“2019年12月12日”)代替2台扫描仪时,它就起作用了

我不知道它从哪里来。。我在用Eclipse


共 (1) 个答案

  1. # 1 楼答案

    以不同格式输入日期时,将发生此错误。您需要以dd/mm/yyyy格式输入日期

        Scanner sc1 = new Scanner (System.in);
        System.out.println("Enter Date1:");
        String date1 = sc1.nextLine();
        System.out.println("Enter Date2:");
        String date2 = sc1.nextLine();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            LocalDate dateDebut = LocalDate.parse(date1,formatter);
    
            System.out.println(dateDebut);
          //  a1.setDateDeb(dateDebut);
            LocalDate dateFin = LocalDate.parse(date2,formatter);
    
            System.out.println(dateFin);
          //  a1.setDateFin(dateFin);
    

    当我们运行上述代码时,它将提示输入2个日期

    输出: 输入日期1: 05/05/2025 输入日期2: 2022年10月1日

    2025-05-05 2022-10-01