0

I have this method called stockNames. The method takes HTML data as a String. The idea is to use Jsoup to get the span out of it. But the for loop in 'stockName' prints out nothing. I tried other StackOverflow answers but did not get a solution. What am I doing wrong? String htmlData is an HTML file put into String.

  public class QuoteTracer extends JFrame {
/**
 *
 */
private static final long serialVersionUID = 1L;

// create text boxes
JLabel labelOne = new JLabel("");
JLabel labelTwo = new JLabel("");
JLabel labelThree = new JLabel("");

public QuoteTracer() {
    super("Stock Traker - By Keb");

    this.setSize(800, 1000);
    this.setLookAndFeel();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    GridLayout gridLayout = new GridLayout(0, 1);
    this.setLayout(gridLayout);

    this.setVisible(false);

    this.add(this.labelOne);
    this.add(this.labelTwo);
    this.add(this.labelThree);

}

// needed for to customize our frame
private void setLookAndFeel() {
    try {
        UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (Exception exc) {
        // do nothing
    }

}

/*
 * given the url 1) get the websites info in html format into a string 2)
 * creates a file to save the html file
 */
public String stockDataGetter() {

    //
    String data = "";

    try {
        URL url = new URL("http://money.cnn.com/data/markets/");
        java.io.InputStream is = url.openStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = br.readLine()) != null) {

            data += line + "\n";
        }

        br.close();
        is.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // outputing to file
    try (BufferedWriter buffWrite = new BufferedWriter(
            new FileWriter("StockRSS.txt"))) {

        // write the string on to a file
        buffWrite.write(data);

        buffWrite.close();

    } catch (IOException ex) {
        System.out.println("There is an error with the file");
    }

    return data;

}

public String stockName(String htmlData) {

    Document document = Jsoup.parse(htmlData);
    String stocks = "";
    // why does this print nothing

    for (Element e : document.select("span.title")) {
        System.out.println(e.text());
    }

    return stocks;
}

public void stockUpdater() {
    Boolean found = false;
    String stockData = this.stockDataGetter();
    // String line;

    while (!found) {

        while (!found) {
            if (stockData.toLowerCase().contains("apple".toLowerCase())) {
                // Character x = stockData[6];
                found = true;
            }

        }

        this.labelOne.setText("APPLE             ");
        this.labelOne.setFont(new Font("Serif", Font.BOLD, 34));

        this.labelTwo.setText("GOOGLE            ");
        this.labelTwo.setFont(new Font("Serif", Font.BOLD, 34));

        this.labelThree.setText(stockData);
        this.labelThree.setFont(new Font("Serif", Font.BOLD, 34));

    }
}

public static void main(String[] args) {
    QuoteTracer stock = new QuoteTracer();
    //stock.stockUpdater();
    String datta = stock.stockDataGetter();

    // looks for stock names and their values
     String nameData = stock.stockName(datta);



}

}

HTML example code 
    <!-- BEGIN: Stock --> 
        <li class="row "> 
            <a href="/quote/quote.html?symb=GOOGL" class="stock"> 
                <span title="Google" class="column stock-name">Google</span> 
                <span stream="last_140864" class="column stock-price">1094.70</span> 
                <span stream="changePct_140864" class="column stock-change"><span class="posData">+0.97%</span></span>

            </a> 
        </li>
        <!-- END: Stock --> 
        <!-- BEGIN: Stock --> 
        <li class="row "> 
            <a href="/quote/quote.html?symb=MSFT" class="stock"> 
                <span title="Microsoft" class="column stock-name">Microsoft</span> 
                <span stream="last_205778" class="column stock-price">93.64</span> 
                <span stream="changePct_205778" class="column stock-change"><span class="posData">+0.63%</span></span>

            </a> 
        </li>
        <!-- END: Stock --> 
k copy k
  • 43
  • 7

1 Answers1

1

The key to this is finding the Elements by Span then ClassName.

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author blj0011
 */
public class JavaApplication43
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        try {
            // TODO code application logic here
            Document document = Jsoup.connect("http://money.cnn.com/data/markets/").get();
            //System.out.println(document.toString());
            Elements spanElements = document.getElementsByTag("span");
            List<String> title = new ArrayList();
            List<String> stockPrice = new ArrayList();
            List<String> stockChange = new ArrayList();

            for (Element element : spanElements) {

                switch (element.className()) {
                    case "column stock-name":
                        title.add(element.text());
                        break;
                    case "column stock-price":
                        stockPrice.add(element.text());
                        break;
                    case "column stock-change":
                        stockChange.add(element.text());
                        break;

                }

            }

            Iterator<String> itTitle = title.iterator();
            Iterator<String> itStockPrice = stockPrice.iterator();
            Iterator<String> itStockChange = stockChange.iterator();
            while (itTitle.hasNext() && itStockPrice.hasNext() && itStockChange.hasNext()) {
                System.out.println(itTitle.next() + " : " + itStockPrice.next() + " ::-:: " + itStockChange.next());
            }
        }
        catch (IOException ex) {
            System.out.println(ex.toString());
        }

    }

}
SedJ601
  • 12,173
  • 3
  • 41
  • 59
  • Thank you. This works perfectly. However i am new to programming so is there easier way to make this work without using iterators. To make it simpler to understand? – k copy k Mar 06 '18 at 16:38
  • The 3 different list should be the same size. Just use a regular for loop. – SedJ601 Mar 06 '18 at 16:41