获取多个值并显示它

时间:2015-05-14 08:58:46

标签: java

我正在检查' n'每分钟服务器数量,如果任何服务器关闭,则邮件将被触发给服务器名称已关闭的用户。我面临的问题是,如果多个服务器出现故障,我只能获得一个服务器名称。如何获取所有已关闭的服务器的名称。

   obj = dataAccess.getServers();  //getting the status and links of all servers
   MailServer sender = new MailServer(From,Password);           
   List<String> downserver = new ArrayList();
   for (Map<String, String> objs : obj) { //Iterating for each server
                serverstatus = objs.get("status");
                if (serverstatus.equals("DOWN")) {
                    servername = objs.get("name");
                    statusserver=objs.get("status");
                }

  downserver.add(servername);
  if(!(servername.equals(null))){
        sender.sendMail("Server Status",downserver.get(i),From,To)
   }

2 个答案:

答案 0 :(得分:1)

如果不检查代码的合理性或尝试改进任何内容,您的代码应该看起来更像以下内容(至少)接近您正在尝试的内容:

servers = dataAccess.getServers();
MailServer sender = new MailServer(From,Password);

List<String> downservers = new ArrayList();
for (Map<String, String> server : servers) {
    serverstatus = server.get("status");
    servername = server.get("name");
    if (serverstatus.equals("DOWN") && servername != null) {
        downservers.add(servername);
    }
}

StringBuilder sb = new StringBuilder();
String sep = "";
for (server : downservers) {
    sb.Append(sep).Append(server);
    sep = ", ";
}
sender.sendMail("Server Status", sb.ToString(), From, To);

或短暂的一次迭代:

MailServer sender = new MailServer(From,Password);
StringBuilder sb = new StringBuilder();
String sep = "";
for (Map<String, String> server : dataAccess.getServers()) {
    String servername = server.get("name");
    if (server.get("status").equals("DOWN") && servername != null) {
        sb.Append(sep).Append(servername);
        sep = ", ";
    }
}
sender.sendMail("Server Status", sb.ToString(), From, To);

答案 1 :(得分:0)

如果要对字符串进行null检查,则不应执行servername.equals(null),如果servername为null,则会抛出NullPointerException。您可以使用if (servername != null)

您也可以在sendMail方法中使用变量servername而不是downserver.get(i)

检查您是否收到NullPointerException或其他例外情况。