Sunday, 15 September 2013

Scanners and multiple if statements

Scanners and multiple if statements

I am trying to get a Scanner to read through each line of data and only
print out the lines that contain the word "model" followed by a year
within the boundaries I set. I am not sure if there is a more efficient
way to do this, but I made one Scanner for the whole set of data and then
within that I declared another one that reads each line. I then tried to
set it to look for a String comprised of the word "model" plus the year if
the line contains the right year. Since tokens in Scanners are divided by
spaces, I thought the correct way to do it would to declare a different
String, tokenToken, that combines the first token with a space and the
year, if such a combination exists.
Currently when I run it, it just runs forever, not compiling, so I don't
know what's wrong with it. I think it may have to do with the innermost if
statement but I'm not sure. I'm new to this.
public static void main(String[] args) {
Scanner inStream = new Scanner(System.in);
while (inStream.hasNext()) {
String line = inStream.nextLine();
Scanner lineStream = new Scanner(line);
while (lineStream.hasNext()) {
String token = lineStream.next();
if (token.matches("model") && lineStream.hasNextInt()) {
int year= lineStream.nextInt();
if ((year>= 1976) && (year <= 2013)) {
String tokenToken = (token + " " + year);
if (lineStream.hasNext(tokenToken)) {
System.out.println(line);
} else {
}
}
}
}
lineStream.close();
}
inStream.close();
}

No comments:

Post a Comment