我正在嘗試學習Java,並且正在玩變量以及爲我想到的基本程序的短程遊戲。我的目標是使用主要方法來打印出我用其他方法收集的數據。我相信答案是非常明顯的,我已經閱讀了Java文檔,但仍然困惑於爲什麼這不起作用。當我運行程序時,它似乎運行時不打印我想要的數據。此外,如果我向spfivehundred方法添加sysout語句,而不是顯示spfivehundred方法無限循環並打印我想要從主方法中取出的數據。你如何正確地返回變量
import com.jaunt.*;
import com.jaunt.component.*;
public class mainthread {
public static void main(String[] args) {
spfivehundred();
double spfivehundreded = spfivehundred();
System.out.println(spfivehundreded);
}
public static double spfivehundred() {
UserAgent userAgent = new UserAgent();
try {
userAgent.visit("http://www.investing.com/indices/us-spx-500");
String spfivehundredget = userAgent.doc.findFirst(
"<span class=\"arial_26 inlineblock pid-166-last\">")
.getText();
double spfivehundred = Double.parseDouble(spfivehundredget.replace(
",", ""));
} catch (JauntException e) {
System.err.println(e);
}
return spfivehundred();
}
}
這將有助於如果您不重用名稱('spfivehundred'),即使在技術上合法。你的return語句再次調用該函數。 – chrylis
'return spfivehundred();'執行遞歸調用,即無限期地調用它自己。它應該是'return spfivehundred;'你需要在'try'' catch'塊之前聲明'spfivehundred'。 –