Create variable names using a loop in Java?

2019-04-29 02:23发布

问题:

first time poster, long time reader so be gentle with me :)

See the following code which works to generate me timestamps for the beginning and end of every month in a 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,0,0);
    Long start = cal.getTimeInMillis();
    cal.clear();
    cal.set(earlyYear,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(earlyYear,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
}
int[] lateMonths = {0, 1, 2, 3, 4, 5, 6, 7}; // Jan to Aug
for (int i : lateMonths) {
    month = i;
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(year,month,1,0,0,0);
    Long start = cal.getTimeInMillis();
    cal.clear();
    cal.set(year,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(year,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
}

So far so good, but in order to use these results I need these timestamps to be output to variables named by month (to be used in a prepared statement later in the code. e.g. SeptStart = sometimestamp, SeptEnd = some timestamp etc etc.

I don't know if it is possible to declare new variables based on the results of each loop. Any ideas?

回答1:

Why not use a Map?

After all you want to have a "container" for some value and address it with a specified name.

So just make the "variable name" your key and "variable value" your, ehm, value.

Edited because you wanted a Sorted collection:

First of all, go for a Treemap instead of a Map.

Also, to preserve lexicograph order, normalize your month number padding zeroes to the left, and use "begin" and "end" as delimiters

So you will have:

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

which will get printed in the correct order when you visit the treemap.



回答2:

Instead of generating variable names, use a Map, where the key is a month name, and the value is the value for that month.

Instead of Date septStart = some date you can do startDates.put("September", some date)

Or better yet, store the values in an array, where the index is the month number: startDates[8] = some date // 0-indexed!



回答3:

You can't declare variables dynamically. I'd suggest to declare two arrays of timestamps (one for the beginnings and one for the endings) and fill them. Then either use these arrays instead of named variables or declare the variables by hand and set them manually.

Calendar[] beginnings = new Calendar[12];
Calendar[] endings = new Calendar[12];

for (int i: earlyMontsh) {
  // Calc beginning ...
  beginnings[i] = cal;
  cal = Calendar.getInstance(); // Important, create new instance!
  // Calc ending ...
  endings[i] = cal;
}
// ... Same for second loop ...

Calendar janStart = beginnings[0];
Calendar janEnd = endings[0];
Calendar febStart = beginnigs[1];
Calendar febEnd = endings[1];
// .. And so on ...
Calendar decStart = beginnings[11];
Calendar decEnd = endings[11];


回答4:

Storing the values in an array would allow you to access them by the Calendar.Month constants

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Cal {

    Long[] start = new Long[12];
    Long[] end = new Long[12];

    private void init(int year) {
        for (int month = 0; month < 12; month++) {
            Calendar cal = Calendar.getInstance();
            cal.clear();
            cal.set(year, month, 1, 0, 0, 0);
            start[month] = cal.getTimeInMillis();
            cal.clear();
            cal.set(year, month, 1);
            int lastDayofMonth = cal
                    .getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
            cal.set(year, month, lastDayofMonth, 23, 59, 59);
            end[month] = cal.getTimeInMillis();
        }
    }

    public static void main(String[] args) {
        Cal cal = new Cal();
        cal.init(2010);

        System.out.println( "start:" + cal.start[Calendar.JANUARY]+ " - " + cal.end[Calendar.JANUARY ]);
    }

}


回答5:

A map does indeed seem to be a good solution :) I am new to java / jsp (and most programming in general!) so I was not aware of how simple this is :)

The following code:

// Financial year runs from Sept-Aug so earlyMonths are those where year = FY-1 and lateMonths are those where year = FY
HashMap hm = new HashMap();
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,0,0);
    Long start = cal.getTimeInMillis();
    hm.put(month + "_start", new Long(start));
    cal.clear();
    cal.set(earlyYear,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(earlyYear,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
    hm.put(month + "_end", new Long(end));
}
int[] lateMonths = {0, 1, 2, 3, 4, 5, 6, 7}; // Jan to Aug
for (int i : lateMonths) {
    month = i;
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(year,month,1,0,0,0);
    Long start = cal.getTimeInMillis();
    hm.put(month + "_start", new Long(start));
    cal.clear();
    cal.set(year,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(year,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
    hm.put(month + "_end", new Long(end));
}
Set set = hm.entrySet();
Iterator hmi = set.iterator();
while(hmi.hasNext()){
    Map.Entry me = (Map.Entry)hmi.next();
    out.println(me.getKey() + " : " + me.getValue() + "<br>");
}

Gives me the following output:

4_end : 1275350399000
3_start : 1270080000000
8_end : 1254355199000
10_start : 1257033600000
1_start : 1264982400000
2_start : 1267401600000
8_start : 1251763200000
10_end : 1259625599000
0_start : 1262304000000
7_start : 1280620800000
0_end : 1264982399000
4_start : 1272672000000
5_start : 1275350400000
11_end : 1262303999000
5_end : 1277942399000
6_start : 1277942400000
9_start : 1254355200000
3_end : 1272671999000
2_end : 1270079999000
9_end : 1257033599000
11_start : 1259625600000
1_end : 1267401599000
7_end : 1283299199000
6_end : 1280620799000

I was curious why it was ordered in such a way? It's not important as far as the functionality is concerned, but for debugging purposes is it possible to order the hashmap?

Thanks for the great suggestions all round folks :)



回答6:

For completion, I post the full code. It pulls availability information about our production servers from a database for a management report. It's the most complicated thing I have done in JSP yet :)

I am sure lots of things could be done more elegantly, so please feel free to advise :) (obviously db passwords etc are XXX'ed out)

<%@page language="java" contentType="text/html"%>
<%@page import="java.util.*,java.sql.*,java.text.*"%>
<html>
<head>
    <title>KPI: FY10</title>
    <link rel="stylesheet" type="text/css" href="reports.css">
</head>
<%
// Example SQL "select count(timestamp) from jagel_hq_log where timestamp > 1270080000000 and timestamp < 1272671999000 and kpi_id = 9"

/* ------------- START CONFIGURABLE VARIABLES -------------*/

int year = 2010;
boolean leapYear = false;
String db_user = "XXXX";
String db_pass = "XXXX";

// Special Case of Leap Years
int febMins;
if(leapYear=true) {
    febMins = 41760;
    }
    else {
    febMins = 44640;    
    }

int yearMins;
if(leapYear=true) {
    yearMins = 527040;
    }
    else {
    yearMins = 525600;
    }
int minsYear = yearMins;

// minutes in each month
int minsJan = 44640;
int minsFeb = febMins;
int minsMar = 44640;
float minsApr = 43200;
int minsMay = 44640;
int minsJun = 43200;
int minsJul = 44640;
int minsAug = 44640;
int minsSep = 43200;
int minsOct = 44640;
int minsNov = 43200;
int minsDec = 44640;

String maxAvail = "#CDEB8B";
String medAvail = "#FFFF88";
String minAvail = "#FDE8D7";
String colour;


/* ------------- END CONFIGURABLE VARIABLES -------------*/

/* Initialise Variables */
int month = 0;
int lastDayofMonth;
int totalMins = 0;
float mins_down = 0;
float avail = 0;
DecimalFormat round = new DecimalFormat("###.###");
Long startTime;
Long endTime;

// Connect to DB
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String connString="jdbc:oracle:thin:@XXXXXXXX.XXXXX.com:XXXX:XXXXXX";
Connection conn = DriverManager.getConnection(connString,db_user,db_pass);

/* Get months of year as 'to' and 'from' timestamps */
// Financial year runs from Sept-Aug so earlyMonths are those where 'year = FY-1' and lateMonths are those where 'year = FY'
HashMap hm = new HashMap();
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,0,0);
    Long start = cal.getTimeInMillis();
    hm.put(month + "_start", new Long(start));
    cal.clear();
    cal.set(earlyYear,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(earlyYear,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
    hm.put(month + "_end", new Long(end));
}
int[] lateMonths = {0, 1, 2, 3, 4, 5, 6, 7}; // Jan to Aug
for (int i : lateMonths) {
    month = i;
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(year,month,1,0,0,0);
    Long start = cal.getTimeInMillis();
    hm.put(month + "_start", new Long(start));
    cal.clear();
    cal.set(year,month,1);
    lastDayofMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
    cal.set(year,month,lastDayofMonth,23,59,59);
    Long end = cal.getTimeInMillis();
    hm.put(month + "_end", new Long(end));
}
%>

<!-- Header -->
<a href="index.jsp"><-- Back to Index</a><br>
<div align="center">
<h2>IITP Availability Report</h2>
<%
Calendar c = Calendar.getInstance();
out.println("Report Generated: " + c.getTime() + " and accurate up to (and including) yesterday");
%>
</div>

<!-- Start Table -->
<table class="mar">
<tr>
    <th class="header">KPI Name</th>
    <th class="header">Description</th>
    <th class="header" colspan="2">Sep <% out.println( year - 1 ); %></th>  
    <th class="header" colspan="2">Oct <% out.println( year - 1 ); %></th>  
    <th class="header" colspan="2">Nov <% out.println( year - 1 ); %></th>
    <th class="header" colspan="2">Dec <% out.println( year - 1 ); %></th>
    <th class="header" colspan="2">Jan <% out.println( year ); %></th>
    <th class="header" colspan="2">Feb <% out.println( year ); %></th>
    <th class="header" colspan="2">Mar <% out.println( year ); %></th>
    <th class="header" colspan="2">Apr <% out.println( year ); %></th>
    <th class="header" colspan="2">May <% out.println( year ); %></th>
    <th class="header" colspan="2">Jun <% out.println( year ); %></th>
    <th class="header" colspan="2">Jul <% out.println( year ); %></th>
    <th class="header" colspan="2">Aug <% out.println( year ); %></th>
    <th class="header" colspan="2">Avg <% out.println( year ); %></th>
</tr>
<tr>
    <th class="top">&nbsp</th>
    <th class="top">&nbsp</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
    <th class="top">Mins Down</th>
    <th class="top">% Avail</th>
</tr>
<%
// Get all KPI_ID's
Statement stmt = conn.createStatement();
ResultSet rs_id = stmt.executeQuery("select distinct (KPI_ID) from JAGEL_KPI_SPECS order by KPI_ID");

// initialise Result Set
ResultSet rs_minsDown;

while (rs_id.next()){
    int id = rs_id.getInt("KPI_ID");

    // Get the kpi name and description from db
    PreparedStatement ps_names = conn.prepareStatement("select KPI_ID, KPI_GROUP_NAME, DESCRIPTION from JAGEL_KPI_SPECS where KPI_ID = " + id);
    ResultSet rs_names = ps_names.executeQuery();
    while (rs_names.next()) {
        out.println("<tr><td>" + rs_names.getString("KPI_GROUP_NAME") + "</td><td>" + rs_names.getString("DESCRIPTION") + "</td>");
    }
    rs_names.close();

    // get the number of minutes down for each month and availability %
    PreparedStatement ps_minsDown = conn.prepareStatement("select count(timestamp) from jagel_hq_log where timestamp > ? and timestamp < ? and kpi_id = " + id);
    //September
    startTime = (Long) hm.get("8_start");
    endTime = (Long) hm.get("8_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsSep*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //October
    startTime = (Long) hm.get("9_start");
    endTime = (Long) hm.get("9_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsOct*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //November
    startTime = (Long) hm.get("10_start");
    endTime = (Long) hm.get("10_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsNov*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }   
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //December
    startTime = (Long) hm.get("11_start");
    endTime = (Long) hm.get("11_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsDec*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //January
    startTime = (Long) hm.get("0_start");
    endTime = (Long) hm.get("0_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsJan*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //February
    startTime = (Long) hm.get("1_start");
    endTime = (Long) hm.get("1_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsFeb*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //March
    startTime = (Long) hm.get("2_start");
    endTime = (Long) hm.get("2_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsMar*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //April
    startTime = (Long) hm.get("3_start");
    endTime = (Long) hm.get("3_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsApr*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //May
    startTime = (Long) hm.get("4_start");
    endTime = (Long) hm.get("4_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsMay*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //June
    startTime = (Long) hm.get("5_start");
    endTime = (Long) hm.get("5_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsMay*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //July
    startTime = (Long) hm.get("6_start");
    endTime = (Long) hm.get("6_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsJul*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //August
    startTime = (Long) hm.get("7_start");
    endTime = (Long) hm.get("7_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsAug*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
    //YEAR
    startTime = (Long) hm.get("8_start");
    endTime = (Long) hm.get("7_end");
    ps_minsDown.setLong(1,startTime);
    ps_minsDown.setLong(2,endTime);
    rs_minsDown = ps_minsDown.executeQuery();
    rs_minsDown.next();
    mins_down = rs_minsDown.getInt("COUNT(TIMESTAMP)");
    avail = 100-(mins_down/minsYear*100);
    if(avail < 99.98) {
        colour=minAvail;
        }
    else if(avail < 100){
        colour=medAvail;
        }
    else {
        colour=maxAvail;
    }
    out.println("<td bgcolor=" + colour + ">" + mins_down + "</td><td bgcolor=" + colour + ">" + round.format(avail) + "%");
    rs_minsDown.close();
}
// close remaining result set and connection
rs_id.close();
conn.close();
%>
</table>
<!-- Footer -->
<br><a href="index.jsp"><-- Back to Index</a>
</body>
</html>