如何显示警报设置为明天,我稍后会叫醒你

yi0zb3m4  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(415)

我现在编译代码有问题。我不知道有什么问题,但请帮帮我。这是我必须遵循的指示。

这是我迄今为止完成的代码。

import java.util.Scanner;
import java.time.LocalTime;

public class Monday extends Weekday{

    private String time;

    public static void main (String[] args) {
        Scanner s = new Scanner(System.in);
        Monday m = new Monday();

        String alarmer;
        System.out.print("Enter time for alarm in this format (HH:MM): ");
        alarmer = s.nextLine();

        m.setAlarm(alarmer);
        m.showAlarm();
    }

    public void setAlarm(String time) {
        this.time = time;
        LocalTime alarm = LocalTime.parse(time);
        LocalTime now = LocalTime.now();

        if (alarm.isBefore(now)) {
            System.out.println("I'll wake you up later!");
        }

        else {
            System.out.println("Alarm is set for tomorrow!");
        }
    }
     public String showAlarm() {
        return time;
    }

}

问题是每当我编译它时,它总是会导致这样的结果。

这是预期的结果/输出。

ee7vknir

ee7vknir1#

将字符串解析为localtime时出现问题。请阅读以下内容:https://howtodoinjava.com/java/date-time/java-localtime/

izj3ouym

izj3ouym2#

我为你找到了解决方案,但我也对你的代码做了一些修改。你有一个扩展类。所以你在周一的课上做的,你应该在平日的课上做,这样你就不必每天重复。
您的报警界面

public interface Alarm {

    void setAlarm(String time);
    String showAlarm(); 
}

你周一的课

import java.util.Scanner;

public class Monday extends Weekday{

    public static void main (String[] args) {
        new Monday();
    }

    public Monday()
    {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter time for alarm in this format (HH:MM): ");
        setAlarm(scanner.nextLine());
    }         
}

最后,你的平日课

import java.text.MessageFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Weekday implements Alarm {

    private final String mTimeFormat = "HH:mm";
    private String mTime; // I don't know why you need this. Return value is never used

    @Override
    public void setAlarm(String time) {     

        try
        {
            this.mTime = time;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(mTimeFormat);
            LocalTime alarm = LocalTime.parse(time, formatter);     
            LocalTime now = LocalTime.now();

            if (alarm.isBefore(now)) {
                System.out.println("I'll wake you up later!");
            }else {
                System.out.println("Alarm is set for tomorrow!");
            }
        }
        catch(DateTimeParseException ex)
        {
            System.err.println(MessageFormat.format("Wrong time format with {0}. Excepted time format {1}", time, mTimeFormat));
        }
    }

    @Override
    public String showAlarm() {
        return mTime;
    }
}

看到线了吗 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(mTimeFormat); 这是格式化输入的地方。您可以在这里处理各种类型的日期格式。

相关问题