我的代碼是將RSS feeds添加到列表中 - 並且代碼最初只是從列表中的第一個位置拉出一個feed,然後添加這個對象到另一個列表。JAVA-如何從for循環訪問FOR循環中的變量
這是原代碼:
public static List<Feed> getFeedsFromXml(String xml) {
Pattern feedPattern = Pattern.compile("<feed>\\s*<name>\\s*([^<]*)</name>\\s*<uri>\\s*([^<]*)</uri>\\s*</feed>");
Matcher feedMatch = feedPattern.matcher(xml);
while (feedMatch.find()) {
String feedName = feedMatch.group(1);
String feedURI = feedMatch.group(2);
feeds.add(new Feed(feedName, feedURI));
}
return feeds;
}
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String addXmlFeed() throws IOException
{
int i = 0;
String stringXml = "<feed><name>SMH Top Headlines</name><uri>http://feeds.smh.com.au/rssheadlines/top.xml</uri></feed><feed><name>UTS Library News</name>";
getFeedsFromXml(stringXml);
Feed f = (Feed) feeds.get(0);
feedList.add(f);
String handler = "You have successfully added: \n";
String xmlStringReply = "" + f + "\n";
feedList.save(feedFile);
return handler + xmlStringReply;
}
一切都進行得很好,然後我決定實現一個for循環處理一個以上飼料的添加到列表中,我嘗試了以下(
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String addXmlFeed() throws IOException
{
int i = 0;
String stringXml = "<feed><name>SMH Top Headlines</name><uri>http://feeds.smh.com.au/rssheadlines/top.xml</uri></feed><feed><name>UTS Library News</name>";
getFeedsFromXml(stringXml);
for (Feed feed: feeds)
{
Feed f = (Feed) feeds.get(i++);
feedList.add(f);
String handler = "You have successfully added: \n";
String xmlStringReply = "" + f + "\n";
}
feedList.save(feedFile);
return handler + xmlStringReply;
}
現在,我敢肯定,這是一個基本的問題,但現在在該行:
return handler + xmlStringReply;
只對有問題的第二種方法)的代碼3210
handler
和xmlStringReply
無法解析爲變量,因爲它們在FOR LOOP內。
有沒有簡單的解決方法呢?
請注意,您可能不想覆蓋這些值,但會將一些信息附加到字符串中。 –
@StefanNeubert好點 - 我錯過了'+'的缺席。 – assylias
Downvoter關心評論? – assylias