0

您好,我的日历有问题。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;


        errorDialogue = new Alert(Alert.AlertType.ERROR);
        dialogue = new TextInputDialog();
        Group group = new Group();
        Scene scene = new Scene(group, 650, 500);
        readInput();

        centerX = scene.getWidth() / 2;
        centerY = scene.getHeight() / 2;

}

这是输出日历

4

1 回答 1

3

YearMonth

解析inputYearMonth使用DateTimeFormatterwithM/uu作为模式。然后,您可以从中获取月份和年份

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

class Main {
    public static void main(String[] args) {
        String input = "03/21";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/uu");
        YearMonth ym = YearMonth.parse(input, dtf);
        System.out.println("Month: " + ym.getMonthValue());
        System.out.println("Year: " + ym.getYear());
    }
}

输出:

Month: 3
Year: 2021

从Trail: Date Time了解有关现代日期时间 API 的更多信息。

交互式演示:

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        YearMonth ym = readInput();
        System.out.printf(String.format("Month: %d, Year: %d%n", ym.getMonthValue(), ym.getYear()));
    }

    static YearMonth readInput() {
        Scanner scanner = new Scanner(System.in);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/uu");
        boolean valid;
        YearMonth ym = null;
        do {
            valid = true;
            System.out.print("Enter month and year [MM/yy]: ");
            String input = scanner.nextLine();
            try {
                ym = YearMonth.parse(input, dtf);
            } catch (DateTimeParseException e) {
                System.out.println("This is an invalid input. Please try again.");
                valid = false;
            }
        } while (!valid);
        return ym;
    }
}

示例运行:

Enter month and year [MM/yy]: a/b
This is an invalid input. Please try again.
Enter month and year [MM/yy]: 21/3
This is an invalid input. Please try again.
Enter month and year [MM/yy]: 3/21
Month: 3, Year: 2021
于 2021-03-21T13:52:38.623 回答