gpt4 book ai didi

java - 如何正确扫描LocalDateTime?

转载 作者:行者123 更新时间:2023-12-01 10:21:08 26 4
gpt4 key购买 nike

我们需要使用输入格式

dd.MM. HH:mm

对于扫描仪(不使用额外的变量!),如何将这些扫描值放入开始变量中?

我的程序无法运行。总是打印“无效输入!”虽然我的输入似乎没有错误:

System.out.println("Start:");
sc.nextLine();
sc.findInLine("(\\d\\d)\\.(\\d\\d)\\. (\\d\\d):(\\d\\d)");
try{
MatchResult mr =sc.match();
int month = Integer.parseInt(mr.group(2));
int day = Integer.parseInt(mr.group(1));
int hour = Integer.parseInt(mr.group(3));
int minute = Integer.parseInt(mr.group(4));
LocalDateTime start = LocalDateTime.of(year, month, day, hour, minute);
System.out.println(start);
} catch (IllegalStateException e)
{
System.err.println("Invalid input!");
}

我的输入:

20.08 13:00

最佳答案

在打印 Start: 后,不应调用 sc.nextLine();。这有效地告诉扫描仪读取行 20.08。 13:00 您正在打印并忽略它,因为您没有存储结果。然后,当您调用 findInLine 时,扫描仪会尝试匹配下一个输入行(我猜该行是空的,您只需再次按 Enter 即可)但失败.

然后,由于没有匹配,sc.match()抛出一个IllegalStateException:

Returns the match result of the last scanning operation performed by this scanner. This method throws IllegalStateException if no match has been performed, or if the last match was not successful.

因此更正后的代码将是:

Scanner sc = new Scanner(System.in);
System.out.println("Start:");
// sc.nextLine(); <-- don't do that, this reads and ignore your input
sc.findInLine("(\\d\\d)\\.(\\d\\d)\\. (\\d\\d):(\\d\\d)");
try {
MatchResult mr = sc.match();
int month = Integer.parseInt(mr.group(2));
int day = Integer.parseInt(mr.group(1));
int hour = Integer.parseInt(mr.group(3));
int minute = Integer.parseInt(mr.group(4));

LocalDateTime start = LocalDateTime.of(2015, month, day, hour, minute);
System.out.println(start);
} catch (IllegalStateException e) {
System.err.println("Invalid input!");
}

关于java - 如何正确扫描LocalDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35611653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com