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

发布于 2024-08-29 08:28:12 字数 1292 浏览 5 评论 0原文

第一次发帖,长期读者,所以请对我温柔点:)

请参阅以下代码,该代码可以为我生成一个财政年度中每个月的开始和结束的时间戳。

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 = 有时戳,SeptEnd = 一些时间戳等。

我不知道是否可以根据每个循环的结果声明新变量。

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

橪书 2024-09-05 08:28:12

为什么不使用 Map

毕竟,您希望有一个用于某些值的“容器”,并使用指定的名称对其进行寻址。

因此,只需将“变量名称”设置为键,将“变量值”设置为值即可。

编辑是因为您想要一个排序集合:

首先,选择 树形图而不是地图。

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

这样您将得到:

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

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

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.

染火枫林 2024-09-05 08:28:12

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

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

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

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!

谈场末日恋爱 2024-09-05 08:28:12

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

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

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];
初熏 2024-09-05 08:28:12

将值存储在数组中将允许您通过 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 ]);
    }

}

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

}
看海 2024-09-05 08:28:12

地图确实似乎是一个很好的解决方案:)我是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

我很好奇为什么要这样排序?就功能而言并不重要,但出于调试目的是否可以对哈希图进行排序?

感谢大家提出的宝贵建议:)

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 :)

挽心 2024-09-05 08:28:12

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

我确信很多事情可以做得更优雅,所以请随时提出建议:)(显然数据库密码等已被 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"> </th>
    <th class="top"> </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>

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"> </th>
    <th class="top"> </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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文