使用Java中的循环创建变量名称?

时间:2010-04-19 06:55:19

标签: java dynamic variables loops names

第一次发布海报,长时间读者对我这么温柔:)

请参阅以下代码,该代码用于生成财务年度中每月开始和结束的时间戳。

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();
}

到目前为止一切顺利,但是为了使用这些结果,我需要将这些时间戳输出到以月命名的变量(稍后在代码中用于准备好的语句中。例如SeptStart = sometimestamp,SeptEnd = some timestamp etc等

我不知道是否可以根据每个循环的结果声明新变量。有任何想法吗?

6 个答案:

答案 0 :(得分:7)

为什么不使用Map

毕竟你想拥有某个值的“容器”并用指定的名称对它进行寻址。

因此,只需将“变量名称”作为您的密钥,将“变量值”设为您的,即ehm值。

编辑,因为你想要一个Sorted集合:

首先,请转到Treemap而不是地图。

另外,要保留字典顺序,请将月份数字填充零标准化为左侧,并使用“开始”和“结束”作为分隔符

所以你会:

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

当您访问树形图时,将以正确的顺序打印。

答案 1 :(得分:3)

使用Map代替生成变量名称,其中键是月份名称,值是该月份的值。

而不是Date septStart = some date,您可以startDates.put("September", some date)

或者更好的是,将值存储在数组中,其中索引是月份数:startDates[8] = some date // 0-indexed!

答案 2 :(得分:1)

您无法动态声明变量。我建议声明两个时间戳数组(一个用于开头,一个用于结尾)并填充它们。然后使用这些数组而不是命名变量或手动声明变量并手动设置它们。

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];

答案 3 :(得分:1)

将值存储在数组中将允许您通过Calendar.Month常量

访问它们
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 ]);
    }

}

答案 4 :(得分:0)

地图确实似乎是一个很好的解决方案:)我不熟悉java / jsp(以及大多数编程!)所以我不知道这有多简单:)

以下代码:

// 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>");
}

给我以下输出:

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

我很好奇为什么以这种方式订购?就功能而言,它并不重要,但出于调试目的,是否可以对hashmap进行排序?

感谢各界人士提出的好建议:)

答案 5 :(得分:0)

完成后,我发布完整的代码。它从数据库中提取有关我们的生产服务器的可用性信息,以获取管理报告。这是我在JSP中做过的最复杂的事情:))

我相信很多事情都可以做得更优雅,所以请随时提出建议:)(显然db密码等是XXX出来的)

<%@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>