如何修复网络碎片值的无限打印



如果这是一个新手问题,很抱歉。实际上,我正在使用这个项目来自学Java。我的程序本质上是一个web scraper,它收集并输出股票的许多不同指标。这个程序运行得很好,直到我意识到我需要能够在许多其他类中调用我的变量。在尝试重写代码以实现这一点之后,我注意到该值将在控制台上输出无限多次。起初,我认为这是因为我的if-else语法,但事实并非如此。有人能帮我弄清楚如何只打印一次值,并确保它在我的其他类中可用吗?

这是我的代码:

package datacollection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
public class Tester
{
public static String fetchMarketCap()
{
final String keyMetricsURL = "https://markets.businessinsider.com/stocks/ko-stock";
// obtains the market cap value
try {
Document marketCapDocument = Jsoup.connect(keyMetricsURL).get();

for (Element row : marketCapDocument.select("div.snapshot")) {
if (row.select("div.snapshot__data-item:nth-of-type(3)").text().equals("")) {
continue;
}
else
{
final String marketCapValue = row.select("div.snapshot__data-item:nth-of- 
type(3)").text();
System.out.println(marketCapValue.substring(0, 8));
}
}
} catch (Exception marketCapDocumentException) {
marketCapDocumentException.printStackTrace();
}
return fetchMarketCap();
}

public static void main(String[] args) throws IOException
{
//call your functions here. this is what the program scans for first and sees which classes and methods to call.
System.out.println(fetchMarketCap());
}

无休止输出的原因是这行代码:

return fetchMarketCap();

它被称为递归。

如果您想重用方法fetchMarketCap((,您可以在一个String中收集结果并将其返回给调用者。

public class Tester {
public static String fetchMarketCap() {
final String keyMetricsURL = "https://markets.businessinsider.com/stocks/ko-stock";
StringBuilder result = new StringBuilder();
try {
Document marketCapDocument = Jsoup.connect(keyMetricsURL).get();
for (Element row : marketCapDocument.select("div.snapshot")) {
if (row.select("div.snapshot__data-item:nth-of-type(3)").text().equals("")) {
continue;
} else {
final String marketCapValue = row.select("div.snapshot__data-item:nth-of-type(3)").text();
result.append(marketCapValue, 0, 8);
}
}
} catch (Exception marketCapDocumentException) {
marketCapDocumentException.printStackTrace();
}
return result.toString();
}
public static void main(String[] args) throws IOException {
//call your functions here. this is what the program scans for first and sees which classes and methods to call.
System.out.println(fetchMarketCap());
}
}

最新更新