I’m attempting to grab data sets from a file named poll.txt and then use relevant data.
The content of the poll.txt:
CT 56 31 7 Oct U. of Connecticut
NE 37 56 5 Sep Rasmussen
AZ 41 49 10 Oct Northern Arizona U.
The source code, ElectoralVotes.java:
import java.io.*;
import java.util.*;
public class ElectionResults {
public static void main(String[] args) throws FileNotFoundException {
int dVotes = 0;
int sVotes = 0;
Scanner scanner = new Scanner(new File("poll.txt"));
String[] nonDigits = new String[29];
int[] Digits = new int[10];
int i = 0;
int j = 1;
while (scanner.hasNextLine()) {
while (scanner.hasNext()) {
nonDigits[i++] = scanner.next();
}
i = 0;
while (j <= 3) {
Digits[i] = Integer.parseInt(nonDigits[j]);
i++;
j++;
}
if (Digits[0] > Digits[1]) {
sVotes += Digits[2];
} else {
dVotes += Digits[2];
}
scanner.nextLine();
}
}
}
However when I run the program, only one of the lines is being used before giving an exception:
Exception in thread "main" java.util.NoSuchElementException: No line found error.
I’ve tried moving around the “scanner.nextLine();” statement to no avail.
The program works fine if I don’t ask for a nextLine but I obviously need it, and I can’t seem to figure out what’s wrong.
You’re calling
scanner.nextLine()at the end of your loop, which will try read the next line. You’re then just throwing away the data!I suspect that’s throwing the exception, because you’ve run out of data. I suspect that your loop of:
is completely consuming the data. (The behaviour of
Scannerhas never been terribly clear to me from the docs, admittedly.) I suspect you should actually be reading a line at a time, with:… and parsing the line separately.