0

about java Scanner

https://code.sololearn.com/c0F47c1sDNrI/#java in this code, i am confused about the scan.nextLine() in the function. it is explained as "to discard the bad data and then displays an error message". if there is no scan.nextLine(), there will be an infinite loop, why.

5th Oct 2020, 9:56 PM
Zhengrong Yan
Zhengrong Yan - avatar
1 Answer
0
there scan.hashNect returns true if there is any input in the inputstream.. And upon reading that input, it will search about next value.. And return true or false if there next input or not.. If you remove scan.readLine() so the next input will not get comsumed and hasNext() will remain and return true only.. So always true makes infinite loop... By the way, loop exits when no more input.. So Again writing for input by this : return scan.nextInt(); will throw error.. And also it should be scan.hasNextInt(), only.. not !scan.hasNextInt()
5th Oct 2020, 10:03 PM
Jayakrishna 🇼🇳