Java程序设计
我有一类WeatherAgent。此类的功能是从世界天气在线的URL(XML代码)中获取当前温度值和其他参数。
我的主要问题是;如何将在WeatherAgent类中生成的温度值转换为其他类(锅炉)?因此,将WeatherAgent类中的XML值作为另一个类(Boiler类)中的新变量进行访问。
package assignment_4;
/*
* imports of class WeatherAgent2
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
*start class WeatherAgent2
*/
public class WeatherAgent {
private Document getDocument() {
Document doc = null;
try {
URL url = new URL(
"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s");
URLConnection connection = url.openConnection(); // Connecting to
// URL specified
doc = parseXML(connection.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
private Document parseXML(InputStream stream) throws Exception
{
DocumentBuilderFactory objDocumentBuilderFactory = null;
DocumentBuilder objDocumentBuilder = null;
Document doc = null;
try
{
objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
doc = objDocumentBuilder.parse(stream);
}
catch (Exception ex)
{
throw ex;
}
return doc;
}
/*
* get the temperature
*/
public double temperature() {
Document doc = getDocument();
Node Temperature;
Double temp = 0.0;
NodeList forecast = doc.getElementsByTagName("temp_C");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list1 = (NodeList) element.getChildNodes();
Temperature = list1.item(0);
temp = Double.parseDouble(Temperature.getNodeValue());
}
return temp;
}
/*
* get cloud cover
*/
public double cloudcover() {
Document doc = getDocument();
Node Cloudcover;
Double cloudcover = 0.0;
NodeList forecast = doc.getElementsByTagName("cloudcover");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list2 = (NodeList) element.getChildNodes();
Cloudcover = list2.item(0);
cloudcover = Double.parseDouble(Cloudcover.getNodeValue());
}
return cloudcover;
}
/*
* print method
*/
public static void main(String[] argvs) {
WeatherAgent wp = new WeatherAgent();
System.out.println("Temperature: " + wp.temperature());
System.out.println("Cloudcover: " + wp.cloudcover());
}
}
我在Boiler类中有此方法,可将WeatherAgent类的温度值转换为Boiler类。
它不起作用,我知道原因。已经感谢您的帮助!
public double getValueFromAgent(){
double agentTemp = send(URL.create("http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s", "temperature" , null, Double.class));
return agentTemp;
}
最佳答案
有一些设计模式可以用来构造类以共享信息。我将研究Observer模式和Mediator模式。
或主要来说,当您从WeatherAgent获得温度时,将其推入锅炉。有了这些,我们的想法就是使锅炉脱离对WeatherAgent的了解。它有助于提高可重用性,并使独立测试它们变得更加容易。