0

我正在做一项作业,我的目标是创建一个类,在给定日期的情况下打印星期几。当提示输入时,如果用户不输入任何内容,程序就会停止。否则,如果用户输入日期,程序会提供星期几,然后继续重新提示用户。用户输入的日期将采用 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 类。

4

2 回答 2

3

尽量减少使用过时的 API

shash678 的回答是正确的,也推荐了您需要使用java.time的长期过时的课程。Calendar我只是想在这里补充一点:即使你需要使用Calendar该类,但这并不一定意味着你也需要使用它过时的朋友DateSimpleDateFormat. 后者可能是所有这些中最麻烦的,当然也是要避免的。

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M d u");
    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();
    LocalDate ld = LocalDate.parse(date, inputFormatter);

    // the easy way to get day-of-week would be ld.getDayOfWeek(),
    // but we are required to use Calendar
    // (any ZoneId will do for atStartOfDay(), I just prefer to provide one)
    Calendar c = GregorianCalendar.from(ld.atStartOfDay(ZoneOffset.UTC));
    int numberOfDayOfWeek = c.get(Calendar.DAY_OF_WEEK);

    // display
    DayOfWeek dayOfWeek;
    // Calendar’s dayOfWeek starts from 1 = Sunday;
    // for DayOfWeek.of() we need to start from 1 = Monday
    if (numberOfDayOfWeek == Calendar.SUNDAY) {
        dayOfWeek = DayOfWeek.SUNDAY;
    } else {
        dayOfWeek = DayOfWeek.of(numberOfDayOfWeek - 1);
    }
    System.out.println("Day of week is "
            + dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.US));

示例会话:

Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.
10 5 2017
Day of week is Thursday

我省略了重复,直到输入一个空行,因为您似乎已经在处理这个问题了。

虽然上述内容肯定不是您的讲师所追求的,但在现实生活中,使用特定过时类的要求通常来自使用需要和/或为您提供该旧类的实例的遗留 API。在这种情况下,我建议您尽量减少对旧 API 的使用,并尽可能地使用现代 API。Calendar因此,在代码中,我仅在找到星期几之前的最后一刻转换为。无论您转换 from DatetoCalendar还是 from LocalDatetoCalendar都不会对代码的复杂性产生太大影响,因此您不妨自己使用现代的LocalDate.

int我确实通过从from转换回Calendar现代枚举来增加一点额外的复杂性DayOfWeek,我用它来显示日期名称。如果你愿意,你可以省略这部分。我包含它只是为了证明有一种方法可以避免在从int日期名称转换时重新发明轮子。

于 2017-10-04T04:32:30.487 回答
2

不要使用 Calendar 而是使用java.time包:

import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate inputDate;

    while(true){
      System.out.print("Enter a date in the format of MM/dd/yyyy:");
      String date = scanner.next();
      try {
        inputDate = LocalDate.parse(date, formatter);
        break;
      } catch (Exception e) {
        System.err.println("ERROR: Please input the date in the correct format");
      }
    }

    System.out.println("The day of week is " + inputDate.getDayOfWeek().name());
  }
}

示例用法:

Enter a date in the format of MM/dd/yyyy: 92/23/2344
ERROR: Please input the date in the correct format
Enter a date in the format of MM/dd/yyyy: 11/26/2019
The day of week is TUESDAY

但是,如果您确实需要使用 Calendar 并且想要使用类似于您现有代码的内容,请尝试以下操作:

注意确保严格解析的行formatter.setLenient(false);,这样输入必须匹配 EXACT 格式。

import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.Calendar;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    formatter.setLenient(false);
    Date inputDate;

    while(true){
      System.out.print("Enter a date in the format of MM/dd/yyyy:");
      String date = scanner.nextLine();
      try {
        inputDate = formatter.parse(date);
        break;
      } catch (Exception e) {
        System.err.println("ERROR: Please input the date in the correct format");
      }
    }

    Calendar c = Calendar.getInstance();
    c.setTime(inputDate);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

    System.out.println("The day of week is " + days[dayOfWeek - 1]);
  }
}

示例用法:

Enter a date in the format of MM/dd/yyyy: 92/23/2344
ERROR: Please input the date in the correct format
Enter a date in the format of MM/dd/yyyy: 11/26/2019
The day of week is Tuesday
于 2017-10-03T23:24:50.467 回答