扫描仪时间

Time in Scanner

我一直在尝试编写一个应用程序,您可以在其中输入时间和要执行的任务,一旦时间到了 "arrived",它就会打印出您必须做这个任务。这是我已经拥有的:

import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class task {
    Scanner scanner=new Scanner(System.in);
    String taskname;
    DateTimeFormatter timecheck = DateTimeFormatter.ofPattern("HH:mm:ss");
    public task()
    {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalDateTime currenttime = LocalDateTime.now();
        System.out.println("Name of the task:");
        taskname=scanner.nextLine();
        System.out.println("Time at which you want to do that task:");
        LocalDateTime timeofthetask = LocalDateTime.parse(scanner.next());
        if(currenttime==timeofthetask)
        {
            System.out.println("It's time to do the task"+taskname);
        }
    }
}

然后,在主要 class 中,我有一些非常简单的东西,基本上就是 运行 这个 class:

public class MainClass
{   
    public static void main(String [] args)
    {
        task t1=new task();
    }
}

一旦我 运行 这个,一切都非常顺利,直到我尝试输入一个时间,当我 运行 代码时出现错误。错误称为 java.time.format.DateTimeParseException,有人知道我能做什么吗?

首先,由于 parse() 代码容易引发异常,因此您应该将调用包含在 try catch 中。

那么,您的代码运行良好,但您需要以这种格式输入时间:

2007-12-03T10:15:30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence-

如果您想要另一种格式,那么您将需要一个格式化程序。