Popular posts from this blog
17- 6-25 | Fibonacci Series | While(true) is infinite loop untill we break. | InputMismatchException in scanner object | sc.next in catch block.
//17-6-25 //Generate Fibonacci series. 0,1, 1, 2, 3, 5,8 ..... k. where k < n . n is entered by user while(true) literally means "loop forever". The condition inside the while loop ( true ) is always true, so ordinarily, this loop would never terminate on its own. It's an infinite loop . we use break statement to come out of the loop. using a try-catch block around the Scanner.nextInt() InputMismatchException means the Scanner object's nextInt() method (or nextDouble() , nextLong() , etc.) was expecting to read an integer (or a double, long, etc.), but the user typed something that couldn't be parsed as that type . we use sc.next() in the catch block because : clear the buffer and prevent infinite loops . ✅ What sc.next(); does: It consumes (reads and discards) the invalid input token from the buffer, allowing the loop to prompt the user again with a clean buffer.
Comments
Post a Comment