Why can't I use nextLine() or next() after nextInt()? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Why can't I use nextLine() or next() after nextInt()?

Is it a bug? Then why isn't it fixed? If its not, then why oracle hasn't changed it. It would've helped many. Any workarounds? Thanks :D

30th Dec 2017, 1:52 AM
Gammaburst
Gammaburst - avatar
3 ответов
+ 1
Hi nextInt() has no carriage return attached to so you need to clear the Scanner before you can use it again an example would be Scanner input = new Scanner (System.in); int a = input.nextInt(); input.next (); String a = input.nextLine(); hope this helps if you have a problem with a piece of code please post it and I will take a look for you and try to explain
30th Dec 2017, 12:03 PM
[A^dr3w]
[A^dr3w] - avatar
+ 2
nextInt() will grab the next integer value from the input stream. nextLine() will try to grab a whole line at a time all the way to the end of line characters. If you have no other characters after the integer before your new line and carriage return then it makes sense that the nextLine wouldn't work as expected. https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo
30th Dec 2017, 3:22 AM
Kevin Gilkey-Graham
Kevin Gilkey-Graham - avatar
+ 1
Thank you for the help. I was wondering why hasn't Oracle added a carriage return to nextInt() as A^dr3w stated? Is it hard? Or is it just impossible? Sorry, if the question is dumb but I really want to know why haven't they made it easier for the coders.
2nd Jan 2018, 1:50 AM
Gammaburst
Gammaburst - avatar