jonasdahl / inda-minigame

0 stars 0 forks source link

Use for each where applicable #8

Closed lericson closed 10 years ago

lericson commented 10 years ago
for (;;) {
    if (tokenizer.hasNext()) {
        line.add(tokenizer.next().trim());
    } else {
        break;
    }
}

Couldn't this be rewritten using for each?

for (String token : tokenizer) {
    line.add(token.trim());
}
jonasdahl commented 10 years ago

Nope, because tokenizer is a Scanner (input), which cannot be iterated over. But while(tokenizer.hasNext()) { line.add(.....) } would work i think

lericson commented 10 years ago

Interesting that it doesn't work! It's a short-coming of Java, it seems...

You can do it though, you just have to shoe-horn the scanner into an iterable interface like this:

for (String word : new Iterable<String>() { public Iterator<String> iterator() { return new Scanner(System.in); } }) {
    System.out.println("word: " + word);
}

... which is not pretty, but in the given circumstance it might be possible to do it neatly?

-Ludvig

On 18 dec 2013, at 21:54, Jonas Dahl notifications@github.com wrote:

Nope, because tokenizer is a Scanner (input), which cannot be iterated over. But while(tokenizer.hasNext()) { line.add(.....) } would work i think

— Reply to this email directly or view it on GitHub.

jonasdahl commented 10 years ago

Wow! That's a classic Ludde-fix!