当前位置: 首页 > 知识库问答 >
问题:

列表中的日历类型元素

杜良骏
2023-03-14

我必须创建一个程序,打印出日期列表(年、月、日),直到用户选择日期(end_date,稍后转换为end_cal)。

例如,如果今天是2017-09-30星期六,并且用户输入日期是2017-10-30,程序必须打印这些日期:

2017-09-30, 2017-10-07, 2017-10-14, 2017-10-21, 2017-10-28.

问题:

  1. 将日历类型元素添加到列表中

当我试图打印它时,输出只是一堆相同日期的副本。

public class Weekdays {
    static Scanner input = new Scanner(System.in);
    static Calendar temp_cal = Calendar.getInstance(); //temporary calendar html" target="_blank">object. it's value is being chaged in the process
    static Calendar start_cal = Calendar.getInstance(); // current day when the program is executed
    static Calendar end_cal = Calendar.getInstance(); //end date that the user inputs


static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

public static boolean date_validation(String date){  //partial validation: whether the input date is in a correct format
    Date test_date;
    try {
        test_date = format.parse(date);

    }catch (ParseException e){
        return false;
        }
    return true;
}   
//created list of dates that are of the same day of the week (for example all Sundays)
static private List<Calendar> getListOfDates(){
    List<Calendar> dates = new ArrayList<>();
    while (!((temp_cal.get(Calendar.YEAR)>= end_cal.get(Calendar.YEAR))&&(temp_cal.get(Calendar.MONTH) >= end_cal.get(Calendar.MONTH))&&(temp_cal.get(Calendar.DAY_OF_YEAR) >= end_cal.get(Calendar.DAY_OF_YEAR))))
    {   
            temp_cal.add(Calendar.DATE, 7); 
            dates.add(temp_cal);        }
    return dates;
}

static private void printListOfDates(List<Calendar> dates){

            System.out.println(Arrays.toString(dates.toArray()));
}

public static void main(String[] str) throws ParseException{

    String end_date = input.next();

    while(!(date_validation(end_date))){
        end_date = input.next();
    }

    end_cal.setTime(format.parse(end_date));    

    printListOfDates(getListOfDates());

}

输入:2018/01/01

输出(仅复制了一个示例,整个输出只是此示例的几个副本):

JAVAutil。GregorianCalendar[time=1515233525518,areFieldsSet=true,ArealFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id=“Europe/Helsinki”,offset=7200000,DSTSAVAINGS=3600000,useDaylight=true,transitions=118,lastRule=java.util.SimpleTimeZone[id=欧洲/赫尔辛基(id=欧洲/赫尔辛基,偏移量=7200000,DST=7200000,DST=0,startMode=2,startMode=2,startDay=2,startDay=1,StartDayOWeek=1,startDay=1,startDay=2,startDay=1,startDay=1,StartDayOOOwWeek=1,StartDayOwWeek=1,StartDayWeek=1,StartDayOwwwEEEEEk=1,StartWayWeek=1,StartDayEEk=1,StartDayOwwwwEEEEEEEk=1,StartWek=1,StartDayEEE8=1,Start=1,Start=1,Start=1,Start=1,StartDayOwwwwwEEEE,周中的天,月中的上午下午1点,小时0点,日中的小时12点,分钟12点,秒5点,毫秒518点,区域偏移量7200000点,DST偏移量0点]]

共有3个答案

史商震
2023-03-14
import java.util.Date;
import java.time.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class days
{
public static void main (String args[]){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter Dates (Start(yyyy/mm/dd)-End)");
    //example 2017 1 5 -> 5 jan 2017
    getDates(Integer.parseInt(input.next()),Integer.parseInt(input.next()),
                 Integer.parseInt(input.next()),Integer.parseInt(input.next()),
                    Integer.parseInt(input.next()),Integer.parseInt(input.next()));
    /*the input needed example
     * 2017
     * 1
     * 1      -Start date
     * 2017
     * 2
     * 10     -End date
     */

}

public static void getDates(int pYearStart, int pMonthStart, int pDayStart,
                                    int pYearEnd, int pMonthEnd, int pDayEnd){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd");
    int year = pYearStart;
    int month = pMonthStart-1;
    int day = pDayStart;
    Calendar start = new GregorianCalendar(year,month,day);
    int yearEnd = pYearEnd;
    int monthEnd = pMonthEnd-1;
    int dayEnd = pDayEnd;
    Calendar end = new GregorianCalendar(yearEnd,monthEnd,dayEnd);
    System.out.print("Start Date:   ");
    System.out.println(sdf.format(start.getTime()));

    System.out.print("End Date:   ");
    System.out.println(sdf.format(end.getTime()));

    System.out.println("");
    System.out.println("All Dates:");

    boolean sameDate = false;
    int amount = 0;
    do{

        System.out.println(sdf.format(start.getTime()));
        start.add(Calendar.DAY_OF_MONTH, 7);
        amount++;
        if(start.get(Calendar.DAY_OF_MONTH) >= end.get(Calendar.DAY_OF_MONTH) && 
        start.get(Calendar.MONTH) == end.get(Calendar.MONTH)) {
            sameDate = true;}
    }while(sameDate != true);
    System.out.println("No of dates: "+amount);
    }
}

我想这就是你想要的,我没有使用列表,而是根据你的喜好进行更改。

丌官子安
2023-03-14

第一个问题是打印结果的方式:

System.out.println(Arrays.toString(dates.toArray()));

如果您想要格式化日期,则需要使用格式化程序。

private static SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

static private void printListOfDates(List<Calendar> dates){
    for (Calendar date : dates) {
        System.out.println(outputFormat.format(date));
    }
}

第二个问题是,您似乎在getListOfDates的循环中重用了相同的temp_cal对象。这将导致列表中包含同一日历对象的多个副本(该日历对象已被修改多次)。您需要为循环中的每个迭代创建一个新实例。

宰父远
2023-03-14

我不确定这是否适合您(我会将其作为您的任务),但您可以使用LocalDate执行类似的操作:

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("yyyy/MM/dd");
    LocalDate endDate;

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

    System.out.println("Below are the days between the current day and " + endDate);
    printDaysBetween(endDate);
  }

  public static void printDaysBetween(LocalDate end){
    LocalDate start = LocalDate.now();
    while (!start.isAfter(end)) {
      System.out.println(start);
      start = start.plusDays(7);
    }
  }
}

用法示例:

Enter the endDate in the format of yyyy/MM/dd: 2017-10-30
ERROR: Please input the date in the correct format
Enter the endDate in the format of yyyy/MM/dd: 2017/10/30
Below are the days between the current day and 2017-10-30
2017-09-30
2017-10-07
2017-10-14
2017-10-21
2017-10-28
 类似资料:
  • 我试图创建动态下拉,其值是从使用微服务的查找表之一填充,但我已经尝试了许多方式相同,到目前为止,我还没有成功地使其工作。 下面的代码用于调用webservice 这是我的对象类型 仅用于显示目前运行的以下代码 我做了什么我尝试调用webservice在多种方式调用它,尝试铸造服务响应直接使用JSON字符串响应和可能的事情我尝试过。 你能在这里帮忙吗?我们将不胜感激。

  • 我正在使用XPath/CSS和Selenium来定位网站上的元素。我想创建一个方法,在这个方法中,我遍历一个定位器列表(XPath/CSS),然后程序选择哪个有效。换句话说,它从定位器1开始-如果定位器存在,它将返回true并存在循环。否则,它将移动到列表中的下一个定位器。一旦用完所有CSS定位器,它就会转到XPath等等。 目前,我正在考虑如下实施: 然后,我计划为每种定位器类型调用此方法(一次

  • 2.5 列表和元组类型 整数类型、浮点数类型和布尔类型都是最简单的“原子”数据类型,因为这些类型的值 是不可分割的基本数据项。而字符串类型稍微有点复杂,因为字符串可以看成是由许多单字 符组成的有序的集合体,我们可以通过索引操作来深入到字符串内部访问其成员。不过,通 常我们仍然将字符串类型归为简单的基本类型,毕竟构成字符串的成员是非常简单的单字 符。 对于单个数据,我们可以用一个变量来存储。假如程序

  • 我正在对地图执行firestore查询 没有人工作过,任何帮助都是感激的 谢谢你抽出时间

  • 问题内容: 我正在尝试开发一种通用的表加载器,其架构在运行时是已知的。这需要具有包含不同类型的元素的列表,并支持各种get和诸如集方法的类,,。元素我考虑的类型有,,,和,和。每个元素的实际类型在运行时都是已知的,我将它们存储在一个List中,描述其架构以进行进一步处理。 我的问题是:我应该在或中存储这样的元素列表吗?还是有更好的方法来实现此类? 问题答案: 由于您的类的共同祖先是,并且由于不会使

  • 问题内容: 如何进行for循环或列表理解,以便每次迭代都给我两个元素? 输出: 问题答案: 你需要一个实施。 对于Python 2: 或更笼统地说: 在Python 3中,你可以替换为内置函数,然后删除import。 所有信贷蒂诺对他的回答到我的问题,我发现这是非常有效的,因为它只是在列表上循环一次,并在此过程中不会产生任何不必要的名单。 注意:不要将其与Python自己的文档中的pairwise