在Java的Calendar类中,如何获取用户输入的日期而不是当前日期? [英] How can I take a user inputted date instead of the current date in the Calendar class in Java?

查看:80
本文介绍了在Java的Calendar类中,如何获取用户输入的日期而不是当前日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做作业,我的目标是创建一个类,该类在给定日期的情况下打印星期几.当提示输入时,如果用户未输入任何内容,则程序将停止.否则,如果用户输入日期,则程序将提供星期几,然后继续重新提示用户.用户输入的日期将为年月日格式,例如,2017年1月10日为1 10 2017.

I'm working on an assignment, and my goal is to create a class that prints the day of the week given a date. When prompted for input, if the user enters nothing, the program is stopped. Otherwise, if the user enters a date, the program provides the day of the week and then continues to re-prompt the user. The date the user inputs will be in the format of m d y, or for example, 1 10 2017 for January 10th, 2017.

到目前为止,我所需要的一切都满足了,但它使用的是当前的日期,月份和年份,而不是用户输入的日期,月份和年份.

What I have so far does everything I need, except it uses the current day, month, and year instead of the user inputted day, month, and year.

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)的倒数第二个代码块,但是我不知道可以用什么替换它来获取用户输入的日期.

I know what needs to be replaced is the second to last chunk of code that says c.get(Calendar.DAY_OF_WEEK), however I do not know what I can use to replace it in order to get the user inputted date.

我知道还有其他软件包可以解决相同的问题,但是,无论是否喜欢,我都必须使用Calendar类.

I know there are other packages that can solve the same problem, however, I'm required to use the Calendar class whether I like it or not.

推荐答案

不要使用日历,请使用

Don't use Calendar use the java.time package instead:

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并想使用类似于现有代码的内容,请尝试以下操作:

NB 请注意 formatter.setLenient(false); 行,该行可确保严格分析,以使输入必须与EXACT格式完全匹配.

N.B. Pay attention to the line formatter.setLenient(false); which ensures strict parsing, such that input must match the EXACT format.

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

这篇关于在Java的Calendar类中,如何获取用户输入的日期而不是当前日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆