Create variable names using loops in Java?

The first poster, long time readers, so be gentle to me:)

Refer to the following code, which is used to generate time stamps for the beginning and end of each month in the financial year

int year = 2010;
// Financial year runs from Sept-Aug so earlyMonths are those where year = FY-1 and lateMonths are those where year = FY
int[] earlyMonths = {8,9,10,11}; // Sept to Dec
int earlyYear = year -1;
for (int i : earlyMonths) {
    month = i;
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(earlyYear,month,1,0);
    Long start = cal.getTimeInMillis();
    cal.clear();
    cal.set(earlyYear,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(earlyYear,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
}
int[] lateMonths = {0,2,3,4,5,6,7}; // Jan to Aug
for (int i : lateMonths) {
    month = i;
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(year,0);
    Long start = cal.getTimeInMillis();
    cal.clear();
    cal.set(year,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(year,59);
    Long end = cal.getTimeInMillis();
}

So far so good, but in order to use these results, I need to output these timestamps to a variable named month (used later in the code to prepare statements. For example, septstart = sometimestamp, septend = some timestamp, etc

I don't know if I can declare a new variable based on the result of each loop Any ideas?

Solution

Why not use map?

After all, you want to have a "container" to get a value and address it with the specified name

Therefore, just use "variable name" as your key and "variable value" as your, that is, ehm value

Edit because you want a sorted set:

First, go to treemap instead of map

Also, to preserve the dictionary order, normalize the month number to the left with zero padding and use start and end as separators

So you will have:

01_begin
01_end
02_begin
...
10_begin
10_end
...

When you access the tree, it will be printed in the correct order

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>