我正在做一项作业,我的目标是创建一个类,在给定日期的情况下打印星期几。当提示输入时,如果用户不输入任何内容,程序就会停止。否则,如果用户输入日期,程序会提供星期几,然后继续重新提示用户。用户输入的日期将采用 mdy 格式,例如 1 10 2017 表示 2017 年 1 月 10 日。
到目前为止,我所做的一切都可以满足我的需要,除了它使用当前的日期、月份和年份,而不是用户输入的日期、月份和年份。
import java.util.Calendar;
import java.util.Scanner;
public class FindDayOfWeek {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.");
String date = s.nextLine();
while (true) {
if (date.isEmpty()) {
System.exit(0);
}
else {
Calendar c = Calendar.getInstance();
String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Day of week is " + days[c.get(Calendar.DAY_OF_WEEK) - 1]);
System.out.println("Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.");
date = s.nextLine();
}
}
}
}
我知道需要替换的是倒数第二个代码块 c.get(Calendar.DAY_OF_WEEK),但是我不知道我可以用什么来替换它以获取用户输入的日期。
我知道还有其他包可以解决相同的问题,但是,无论我喜欢与否,我都必须使用 Calendar 类。