Help with code.[Job with files] C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Help with code.[Job with files] C++

Given a file, the components of which are structures of the type: day, month, year. Describe a function that checks by today's date (entered from the keyboard), which of the dates in the file is closest to today's date. Дан файл, компонентами которого являются структуры типа: день, месяц, год. Описать функцию, проверяющую по сегодняшней дате (введенной с клавиатуры), какая из дат в файле является ближайшей к сегодняшнему дню

6th Apr 2017, 5:49 AM
mvas
3 Answers
0
package com.company; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; public class Main {    private List<Date> mDates = new LinkedList<>();    public static void main(String[] args) {       Main main = new Main();       main.addDate(2017, 04, 07);       main.addDate(2017, 03, 27);       main.addDate(2017, 02, 15);       main.addDate(2017, 04, 05);       Date today = createDate(2017, 04, 06);       Date closest = main.getClosestDate(today);       System.out.println(closest);    }    private Date getClosestDate(Date date) {       Date closest = mDates.get(0);       long difference = getDifference(date, closest);       for (int i = 1; i < mDates.size(); i++) {          Date next = mDates.get(i);          if (getDifference(date, next) < difference) {             closest = next;          }       }       return closest;    }    private static long getDifference(Date d1, Date d2) {       return Math.abs(d1.getTime() - d2.getTime());    }    private void addDate(int year, int month, intday) {       mDates.add(createDate(year, month, day));    }    private static Date createDate(int year, intmonth, int day) {       Calendar c = Calendar.getInstance();       c.set(year, month - 1, day, 0, 0);       return c.getTime();    } }
6th Apr 2017, 9:15 AM
Kovy
Kovy - avatar
0
File reading and user input is up to you
6th Apr 2017, 9:16 AM
Kovy
Kovy - avatar
0
Thank you!
6th Apr 2017, 11:16 AM
mvas