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

Java线性搜索程序遭遇NoSuchElementException异常求助

问题分析与解决方案

异常原因

你遇到的java.util.NoSuchElementException: No line found异常,根源在于多次创建并关闭Scanner实例:

  • main方法中通过try-with-resources创建的Scanner关联着System.in输入流;
  • inputValues方法内又新建了Scanner并关联同一System.in,且通过try-with-resources自动关闭该Scanner。关闭Scanner时会同时关闭底层的System.in流,导致main方法中原有Scanner后续读取输入时,输入流已关闭,无法获取内容从而抛出异常。

修复方案

全程复用同一个Scanner实例,不要在方法内新建并关闭Scanner,将main中的Scanner作为参数传递给inputValues方法即可。

修复后的完整代码

import java.util.Scanner;
public class LinearSearch {

    public static void main(String[] args) 
    {
        try(Scanner s = new Scanner(System.in))
        {
            System.out.println("Enter no. of times you want to loop");
            int testCases = Integer.parseInt(s.nextLine());
            for(int i=1;i<=testCases;i++)
            {
                System.out.println("Enter size of array");
                int size=Integer.parseInt(s.nextLine());
                int[] arr = new int[size];
                
                arr = inputValues(arr, s); // 传递外部Scanner实例
                
                System.out.println("Enter no. to be searched");
                int find = Integer.parseInt(s.nextLine());
                
                System.out.println("Calling search function");

                int arrayIndex = findIndex(arr, find);
                System.out.println(arrayIndex);
            }
        }
    }

    private static int findIndex(int[] arr, int find) {
        // 优化逻辑:初始设为-1,找到目标直接返回索引,无需重复赋值
        int arrayIndex = -1;
        for (int i=0; i<arr.length; i++)
        {
            if(find == arr[i])
            {
                return i;
            }
        }
        return arrayIndex;
    }
    
    private static int[] inputValues(int[] arr, Scanner s) 
    {
        System.out.println("array length "+arr.length);
        for(int i=0; i<arr.length; i++)
        {
            arr[i]=Integer.parseInt(s.nextLine());
        }
        return arr;
    }
}

关键修改点

  1. 调整inputValues方法参数,接收外部传入的Scanner实例,不再内部新建Scanner;
  2. 移除inputValues方法内的try-with-resources,避免关闭全局输入流;
  3. 优化findIndex方法逻辑:初始将结果设为-1,循环中找到目标值直接返回对应索引,简化代码逻辑并提升效率。

额外说明

try-with-resources会自动关闭实现AutoCloseable接口的资源,Scanner实现了该接口,因此关闭Scanner时会同步关闭关联的输入流。System.in是全局唯一的标准输入流,一旦关闭无法重新打开,因此全程应使用同一个Scanner操作该流。

内容的提问来源于stack exchange,提问作者Harish Prasad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:46:14