java如何输入年月
使用Scanner类从控制台输入年月
在Java中,可以通过Scanner类从控制台获取用户输入的年月数据。需要导入java.util.Scanner包。
import java.util.Scanner;
public class InputYearMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份: ");
int year = scanner.nextInt();
System.out.print("请输入月份: ");
int month = scanner.nextInt();
System.out.println("您输入的是: " + year + "年" + month + "月");
}
}
使用JOptionPane进行图形化输入
如果需要图形化界面输入,可以使用JOptionPane类,需要导入javax.swing.JOptionPane包。
import javax.swing.JOptionPane;
public class InputYearMonthGUI {
public static void main(String[] args) {
String yearInput = JOptionPane.showInputDialog("请输入年份:");
int year = Integer.parseInt(yearInput);
String monthInput = JOptionPane.showInputDialog("请输入月份:");
int month = Integer.parseInt(monthInput);
JOptionPane.showMessageDialog(null, "您输入的是: " + year + "年" + month + "月");
}
}
使用正则表达式验证输入格式
对于需要特定格式的输入(如YYYY-MM),可以使用正则表达式进行验证。
import java.util.Scanner;
import java.util.regex.Pattern;
public class ValidateYearMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年月(格式: YYYY-MM): ");
String input = scanner.nextLine();
if (Pattern.matches("^\\d{4}-(0[1-9]|1[0-2])$", input)) {
System.out.println("输入有效: " + input);
} else {
System.out.println("输入无效,请使用YYYY-MM格式");
}
}
}
使用LocalDate处理年月输入
Java 8及以上版本可以使用java.time.LocalDate来处理日期输入。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class LocalDateInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年月(格式: yyyy-MM): ");
String input = scanner.nextLine();
try {
LocalDate date = LocalDate.parse(input + "-01", DateTimeFormatter.ISO_DATE);
System.out.println("年份: " + date.getYear());
System.out.println("月份: " + date.getMonthValue());
} catch (DateTimeParseException e) {
System.out.println("日期格式错误");
}
}
}
使用YearMonth类专门处理年月
Java 8还提供了YearMonth类专门处理不包含日的年月数据。

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class YearMonthInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年月(格式: yyyy-MM): ");
String input = scanner.nextLine();
try {
YearMonth yearMonth = YearMonth.parse(input, DateTimeFormatter.ofPattern("yyyy-MM"));
System.out.println("年份: " + yearMonth.getYear());
System.out.println("月份: " + yearMonth.getMonthValue());
} catch (DateTimeParseException e) {
System.out.println("日期格式错误");
}
}
}
以上方法涵盖了从基础控制台输入到高级日期处理的多种方式,可以根据具体需求选择适合的方法。






