-1

I need to validate somehow two dates, but I do not know which way is the best. In mainclass I created objects which I are passed by constructor to NBPParserEngine.

package pl.parser.nbp;

import pl.parser.nbp.calculations.RateCalculations;
import pl.parser.nbp.validation.ConditionChecker;
import pl.parser.nbp.validation.ConditionCheckerService;
import pl.parser.nbp.historysystem.HistorySystem;
import pl.parser.nbp.historysystem.HistorySystemService;
import pl.parser.nbp.view.NbpParserView;

import java.time.LocalDate;

public class MainClass {

    public static void main(String[] args) {

        NbpParserView nbpParserView = new NbpParserView();
        DataFetcher dataFetcher = new DataFetcher();
        HistorySystem historySystem = new HistorySystemService();
        RateCalculations rateCalculations = new RateCalculations();
        ConditionChecker conditionChecker = new ConditionCheckerService();
        NBPParserEngine nbpParserEngine = new NBPParserEngine(conditionChecker, dataFetcher, rateCalculations,
                historySystem, nbpParserView);


        String currency = args[0];
        LocalDate startDate = LocalDate.parse(args[1]);
        LocalDate endDate = LocalDate.parse(args[2]);

        nbpParserEngine.executeNbpParserEngine(startDate, endDate, currency);
    }
}

I need to validate if these two dates are good, because if not then DateTimeParseException is thrown. Should I validate it in main with while loop and scanner or which way?

pipilam
  • 587
  • 3
  • 9
  • 22

1 Answers1

1

Use a try-catch statement, for example:

    LocalDate startDate = null;
    try {
        startDate = LocalDate.parse(args[1]);
    } catch (DateTimeParseException dtpe) {
        System.err.println("Start date \"" + args[1] + "\" is not a valid date.");
        System.exit(-1);
    }

Do similarly for end date.

Search java exception handling or similar to learn more.

And yes, if your program is interactive, an alternative to reading the dates from the command line is reading from standard input using a scanner and looping until a valid date is entered. Again I think that a search will lead you to the building blocks you need for putting it together.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161