Reputation: 53
I need to reads the number of words on http://cs.armstrong.edu/liang/data/Lincoln.txt. I wrote my program, and NetBeans isn't giving me any errors. However, the program seems to be infinite. It does not stop trying to execute, and ultimately no answer is given (or even calculated, I'm not sure). Below is the code.
import java.net.*;
import java.util.Scanner;
import java.io.IOException;
public class readDataFromWeb {
public static void main(String[] args) {
try {
URL url = new URL("http://cs.armstrong.edu/liang/data/Lincoln.txt");
int wordCount = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
wordCount++;
}
System.out.println(url + " has " + wordCount + " words.");
}
catch (MalformedURLException ex) {
System.out.println("Invalid URL");
}
catch (IOException ex) {
System.out.println("I/O Errors: No such file");
}
}
}
I'm under the impression that at first, the variable url of type URL is declared and set to http://cs.armstrong.edu/liang/data/Lincoln.txt. Is this where I am going wrong? Have I entered something incorrectly? I can provide more information if necessary. Any stylistic or conceptual insights are also welcome; I'm trying to learn. Thanks!
Upvotes: 1
Views: 74
Reputation: 58848
You never actually read any words from the scanner. hasNext
returns true because there's a word you could read... but you never actually read it, so it keeps being ready for you to read, so hasNext
keeps returning true.
Just call input.next()
inside the loop.
Upvotes: 2