java.util.scanner - Scanner nextLine issue in Java -



java.util.scanner - Scanner nextLine issue in Java -

this question has reply here:

scanner issue when using nextline after nextxxx [duplicate]

just 1 question: why must type answer = in.nextline(); twice? if line single programme doesn't work expected. without sec line programme doesn't inquire come in string.

public class main { public static void main(string[] args) { scanner in = new scanner(system.in); string reply = "yes"; while (answer.equals("yes")) { system.out.println("enter name , rating:"); string name = in.nextline(); int rating = 0; if (in.hasnextint()) { rating = in.nextint(); } else { system.out.println("error. exit."); return; } system.out.println("name: " + name); system.out.println("rating: " + rating); ects ects = new ects(); rating = ects.checkrating(rating); system.out.println("enter \"yes\" continue: "); reply = in.nextline(); reply = in.nextline(); } system.out.println("bye!"); in.close(); } }

the scanner-object has internal cache.

you start scann nextint(). you press key 1 you press key 2 you press return

now, internal cache has 3 characters , scanner sees 3rd character(return) not number, nextint() homecoming integer 1st , 2nd character (1,2=12).

nextint() returns 12.

unfortunately return still part of scanner's cache.

you phone call nextline(), method scans cache newline-marker has been kept in cache before nextint() phone call returned.

the nextline() returns 0-length-string.

the next nextline() has empty cache! wait until cache has been filled next newline-marker. reset()

there more elegant way clear cache instead of using nextline():

in.reset();

java java.util.scanner

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -