cs50 / libcs50-java

CS50 Library for Java
GNU General Public License v3.0
18 stars 11 forks source link

stdin consumed where shouldn't #17

Closed kzidane closed 7 years ago

kzidane commented 7 years ago

A Scanner object may buffer all data in System.in, preventing subsequent Scanner(s) from accessing the rest of the lines (since they were consumed by previous Scanner), and therefore losing those lines. This can be replicated by redirecting stdin to a file.

http://stackoverflow.com/a/4232614/1797347

Foo.java:

import edu.harvard.CS50;

class Foo {
    public static void main(String[] args) {
        String s = CS50.getString("");
        while (s != null) {
            System.out.println(s);
            s = CS50.getString("");
        }
    }
}

data.txt:

foo
bar
baz

Output:

$ javac Foo.java
$ java Foo < data.txt
foo
dmalan commented 7 years ago

@kzidane, how about this?

https://github.com/cs50/libcs50-java/pull/18/commits/d8d023a7daae4c40ff1766fa5fec1ccb82b4e762#diff-acf6a41e9d226f255b68a55d3b0e193dR66

Since all get* methods call getString, seems okay to initialize Scanner once up top?

kzidane commented 7 years ago

I mean this still creates a Scanner instance unnecessarily if the user just imports edu.harvard.CS50, and never calls any of the get*, but probably nbd. Let's :shipit:!

On Sun, May 14, 2017, 6:45 PM David J. Malan notifications@github.com wrote:

@kzidane https://github.com/kzidane, how about this?

cs50/libcs50-java@d8d023a#diff-acf6a41e9d226f255b68a55d3b0e193dR66 https://github.com/cs50/libcs50-java/commit/d8d023a7daae4c40ff1766fa5fec1ccb82b4e762#diff-acf6a41e9d226f255b68a55d3b0e193dR66

Since all get* methods call getString, seems okay to initialize Scanner once up top?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/cs50/libcs50-java/issues/17#issuecomment-301324573, or mute the thread https://github.com/notifications/unsubscribe-auth/AG5TA88hcB-4ggTz8eSVlTBWuW5f9hbvks5r5y-jgaJpZM4NaD32 .

dmalan commented 7 years ago

Just did a test, actually, and scanner should only be initialized if the class is actually referenced, not just imported!

kzidane commented 7 years ago

Ah, it seems to be instantiated when class is initialized per http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1. Sorry I forgot! :innocent: