+ 1

Need help dubugging Java code

Hi. I have been working on some code to check whether a word is part of dictionary.com's dictionary via a URL check. Not sure why I am getting an error at this point. Any help would be appreciated. Code is below: import java.io.*; import java.net.*; public class Program { public static void main(String[] args) { String url = "http:////dictionary.com//browse//"; String word = "plop"; try{URL dicti = new URL(url + word); } catch(MalformedURLException e) { System.out.println("error"); } BufferedReader br = new BufferedReader(new InputStreamReader(dicti.openStream())); String line = br.readLine(); while (line != null) { System.out.println(line); } } }

2nd Jun 2017, 4:38 PM
John Fentiman
John Fentiman - avatar
3 Answers
+ 4
2 questions: * Is this done on code playground? If so, unfortunately you cannot connect to urls on code playground with java. * What is the error specifically saying? Also, I don't think that while loop is doing what you think it's doing. That's gonna be an infinite loop if the string isn't null. What you are looking for is likely: while((line = br.readLine()) != null) Or, If bufferred reader has this method: while(br.hasNext()) (I'm not sure if it has that or not)
2nd Jun 2017, 4:52 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
Oh, the URL is in the scope of the try block, so when you created the buffered reader it cannot access dicti. Surround everything in the try catch or declare the URL before the try block. Something like this: try{ URL dicti = ......; buffered reader = .....; etc.. }catch(IOException e, MalformedURLException a){ ... } Or, declare the URL outside the try block. Like this: URL dicti; try{ dicti =....; } ...etc
2nd Jun 2017, 5:04 PM
Rrestoring faith
Rrestoring faith - avatar
0
I was trying to do it in code playground, so I guess that is part of the problem. The error I got was this: ..\Playground\:15: error: cannot find symbol BufferedReader br = new BufferedReader(new InputStreamReader(dicti.openStream())); ^ symbol: variable dicti location: class Program 1 error I should change the "while" to an "if" then? Thanks for the help!
2nd Jun 2017, 5:00 PM
John Fentiman
John Fentiman - avatar