Parse input
to YearMonth
using a DateTimeFormatter
with M/uu
as the pattern. Then, you can get the month and year from it
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());
}
}
Output:
Month: 3
Year: 2021
Learn more about the modern date-time API from Trail: Date Time.
An interactive demo:
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;
}
}
A sample run:
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