Sunday, February 26, 2017

Scanner input problem: nextLine combined with next/nextInt/nextDouble


nextInt() or nextDouble() takes one number and leaves "enter" in the
keyboard buffer.

next() takes one word and leaves "enter" in the keyboard buffer.

nextLine() keeps taking characters until "enter" and removes the
"enter" from keyboard buffer. So it effectively takes one sentence /
full name etc.

So, nextLine() written after nextInt() or nextDouble() or next() does
not work as expected because it takes that "enter" only which is left
by previous nextInt()/nextDouble()/next() and finishes its work.

In order to skip that unwanted "enter", use scanner.skip("[\r\n]+")
like in the following example.

//way 1 of 2:

       int n = scanner.nextInt();
        //following line is optional as nextInt/nextDouble/next() can skip "enter"
        scanner.skip("[\r\n]+");
        int m = scanner.nextInt();
        //following line is must, for the nextLine below to work
        scanner.skip("[\r\n]+");
        String fullName = scanner.nextLine();
        out.println("n="+n);
        out.println("m="+m);
        out.println("fullName="+fullName+"=");


//way 2 of 2:

        int n = scanner.nextInt();
        //following line is optional as nextInt/nextDouble/next() can skip "enter"
         scanner.skip("[\r\n]+");
        int m = scanner.nextInt();
        //following line is must for the fullName=..nextLine below to work
        scanner.nextLine();
        String fullName = scanner.nextLine();
        out.println("n="+n);
        out.println("m="+m);
        out.println("fullName="+fullName+"=");


Reference:
http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods

1 comment:

MUSIC_BD said...
This comment has been removed by the author.