【问题标题】:Exception in thread "main" java.time.format.DateTimeParseException: Text '' could not be parsed at index 0 [duplicate]线程“主”java.time.format.DateTimeParseException 中的异常:无法在索引 0 处解析文本“”[重复]
【发布时间】:2020-02-01 01:44:14
【问题描述】:

我有一个扫描仪来获取 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

【问题讨论】:

  • 我无法重现此问题。您遇到错误的具体是哪一行?
  • 在打电话给nextLine之前有没有打电话给nextInt左右?
  • 是的,我还有其他 2 个参数
  • 所以您正在阅读上一行的结尾...可能重复,没有完整代码很难说:stackoverflow.com/a/13102066/85421
  • 你是对的,它正在阅读上一行谢谢

标签: java parsing localdate


【解决方案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: 2025 年 5 月 5 日 输入日期2: 2022 年 1 月 10 日

2025-05-05 2022-10-01

【讨论】:

  • 那是因为我之前有2个scanner.nextLine()。
猜你喜欢
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
相关资源
最近更新 更多