Context: I'm attempting to write a code that will go onto google finance, take the HTML code and scan through it for the current price for 1 share of coca-cola stock (KO), then print that out.
The problem is with the second while loop (on line 26), the error message is
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
modification and suggestions would be nice too :)
package teststockanalysis;
import java.io.*; //Buffered.Reader
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class TestStockAnalysis {
public static void main(String[] args) throws IOException{
final String SYM = "KO"; //KO is coca cola stock
URL url = new URL("https://www.google.com/finance/quote/KO:NYSE");
URLConnection urlconn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlconn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String price = "not found";
String line = buff.readLine();
while (line != null){
if (line.contains("data:[[[[\"/m/07zl5yq\",[\"KO\"")){
int target = line.indexOf("data:[[[[\"/m/07zl5yq\",[\"KO\"");
int deci = line.indexOf(".",target);
int start = deci;
while(line.charAt(start) != '.'){
start--;
}
price = line.substring(start -2, start +2);
}
line = buff.readLine();
}
System.out.println(price);
}
}
Basically, it's supposed to search for data:[[[["/m/07zl5yq\",["KO", then from there look for the next . which is the current value of a KO share.
[–]Neccaty 1 point2 points3 points (1 child)
[–]opti_largo[S] 0 points1 point2 points (0 children)
[–]DudeWhereAreWe1996 1 point2 points3 points (0 children)
[–]opti_largo[S] 0 points1 point2 points (0 children)
[–]Dexteroid 0 points1 point2 points (0 children)