You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序while循环二次迭代出现Scanner NoSuchElementException异常

Fixing Scanner NoSuchElementException in Your Java While Loop

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 close System.in until 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.in stays 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:43:07