Java程序while循环二次迭代出现Scanner NoSuchElementException异常
Hey there, let's break down why you're running into that NoSuchElementException on the second loop iteration—and how to fix it quickly.
The Root Cause
Your current code creates a new Scanner instance inside the while loop and calls sc.close() at the end of each loop. Here's the problem: when you close the Scanner, it doesn't just shut down the Scanner object—it also closes the underlying input stream it's connected to, which is System.in (the console input).
Once System.in is closed, any subsequent attempts to read from it (like creating a new Scanner in the next loop iteration) will fail because the input stream is gone. That's exactly why sc.next() throws the exception the second time around.
The Fix
We need to make two key changes:
- Initialize the Scanner once, outside the while loop (so we reuse the same instance instead of creating new ones).
- Move the
sc.close()call outside the loop (so we don't closeSystem.inuntil we're completely done with all input operations).
Here's your revised code:
import java.util.Scanner; public class YourClassName { public static void main(String[] args) { // Initialize Scanner ONCE outside the loop Scanner sc = new Scanner(System.in); while(true) { System.out.println("Want to repeat :"); if(!sc.next().equalsIgnoreCase("y")) { break; } // Call your methods here // isPrimeNumber(); // fibonacciSeries(); getFactorialOfaNumber(); } // Close Scanner ONLY after we're done with all input sc.close(); } // Make sure your getFactorialOfaNumber() method is defined here private static void getFactorialOfaNumber() { // Your method logic goes here } }
Key Notes
- Reusing the same Scanner instance avoids repeatedly opening/closing the input stream.
- Closing the Scanner after the loop ensures
System.instays open for all iterations of the loop. - If you're using Java 7 or later, you could also use a try-with-resources block to auto-close the Scanner, but for simple console input like this, initializing once and closing at the end is perfectly clean.
内容的提问来源于stack exchange,提问作者Bruce

