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

为何运行Java游戏代码时抛出NoSuchElementException异常?求解决

问题:运行Game.java时抛出NoSuchElementException异常

异常信息

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at ItemGenerator.textFileReaderSpecialItems(ItemGenerator.java:71)
    at ItemGenerator.<init>(ItemGenerator.java:22)
    at Game.<init>(Game.java:9)
    at Game.main(Game.java:16)

相关代码

ItemGenerator.java 部分代码

58    public void textFileReaderSpecialItems(String x) {
59
60        try {
61
62            Scanner fileSc = new Scanner(new File(x));
63            
64            while(fileSc.hasNext() && fileSc != null) {
65
66                String s1;
67                String s2;
68                String s3;
69
70                s1 = fileSc.nextLine();
71                s2 = fileSc.nextLine();
72                s3 = fileSc.nextLine();
73
74                itemsList.add(new Items(s1, s2, s3));
75            }
76
77            fileSc.close();
78        
79        } catch (FileNotFoundException e) {
80
81            System.out.println("\nError: " + e + "\nProgram exiting...\n");
82            System.exit(0);
83        
84        }
85
87    }

Game.java 部分代码

3    public Game() {
4       
5        LocationGenerator newLocationGenerator = new LocationGenerator("Locations.txt");
6        MainCharacterGenerator newMainCharacter = new MainCharacterGenerator("MainCharacter.txt");
7        CharacterGenerator newCharacter = new CharacterGenerator("Characters.txt", "Jabberwocky.txt");
8        ItemGenerator newItem = new ItemGenerator("Items.txt", "SpecialItems.txt");
9        newLocationGenerator.startLocation();
10
11    }     
12
13    public static void main(String[] args) {
14
15        Game game = new Game();
16
17    } 

问题原因及修复方案

原因

  1. 循环条件错误:fileSc.hasNext() 判断的是是否存在下一个空白符分隔的token,而非是否存在下一行,无法保证每次循环都能读取到3行内容。
  2. 未检查行是否存在:每次循环直接调用3次nextLine(),如果文件总行数不是3的倍数,最后一次循环会出现已无行可读但仍调用nextLine()的情况,触发NoSuchElementException。
  3. 多余判断:fileSc != null 毫无意义,new Scanner()成功创建后不会返回null,创建失败会直接抛出FileNotFoundException并被捕获。

修复方案

方案一:每次读取前检查是否有足够的行

修改textFileReaderSpecialItems方法的循环逻辑:

public void textFileReaderSpecialItems(String x) {
    try {
        Scanner fileSc = new Scanner(new File(x));
        
        while (fileSc.hasNextLine()) {
            String s1 = fileSc.nextLine();
            if (!fileSc.hasNextLine()) break;
            String s2 = fileSc.nextLine();
            if (!fileSc.hasNextLine()) break;
            String s3 = fileSc.nextLine();
            
            itemsList.add(new Items(s1, s2, s3));
        }

        fileSc.close();
    
    } catch (FileNotFoundException e) {
        System.out.println("\nError: " + e + "\nProgram exiting...\n");
        System.exit(0);
    }
}

方案二:先读取所有行再分组处理(更稳健)

先将文件所有行读入列表,再按3行一组处理,避免中途无行可读:

import java.util.ArrayList;
import java.util.List;

// ...

public void textFileReaderSpecialItems(String x) {
    try {
        Scanner fileSc = new Scanner(new File(x));
        List<String> allLines = new ArrayList<>();
        
        while (fileSc.hasNextLine()) {
            allLines.add(fileSc.nextLine());
        }
        
        for (int i = 0; i < allLines.size(); i += 3) {
            if (i + 2 >= allLines.size()) break;
            String s1 = allLines.get(i);
            String s2 = allLines.get(i + 1);
            String s3 = allLines.get(i + 2);
            
            itemsList.add(new Items(s1, s2, s3));
        }

        fileSc.close();
    
    } catch (FileNotFoundException e) {
        System.out.println("\nError: " + e + "\nProgram exiting...\n");
        System.exit(0);
    }
}

内容的提问来源于stack exchange,提问作者Hunter Treleaven

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:25:10