String array containing expiration credit card years from current year count 10 more years

Jaime Montoya :

For the expiration date of credit/debit cards, I am using an array that contains all years since 2020 to 2030:

String[] expirationYearArray = { "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030" };

That is a bad approach because years are hard-coded. That means that after 3 years, in 2023, users will still have the option to choose 2020, 2021 and 2022 as the expiration date of credit cards. That is clearly wrong. What I want to do is to fill the array with Strings from current year to 10 more years from the current year. What I am thinking to do is to use a Java built-in function to get the current year. Then use a for loop to make 10 iterations and in each iteration convert from Int to String so that I convert 2020 to "2020" and then push that "2020" as the first element of the expirationYearArray array. The for or while loop would continue to do that until I reach the tenth iteration. Does this approach make sense to you? Please let me know if you see a different or more optimal option that may do the same with less code or if it makes sense to you the way I am envisioning it. Thank you.

Nonika :

Here are several variants:

  public static void main(String[] args) {

    System.out.println(Arrays.toString(getExpirationYears(LocalDateTime.now().getYear())));
    System.out.println(Arrays.toString(getExpirationYears(Calendar.getInstance().get(Calendar.YEAR))));
    System.out.println(Arrays.toString(getExpirationYears(1900 + new Date().getYear())));
    System.out.println(Arrays.toString(getExpirationYearByStreams(1900 + new Date().getYear())));
}

static String[] getExpirationYears(int year) {
    String[] expirationYearArray = new String[10];
    for (int i = 0; i < expirationYearArray.length; i++) {
        expirationYearArray[i] = String.valueOf(year + i);
    }
    return expirationYearArray;
}


static String[] getExpirationYearByStreams(int year) {
   return IntStream.range(year, year+10)
            .boxed()
            .map(String::valueOf)
            .toArray(String[]::new);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193455&siteId=1