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

NetBeans中读取文本文件遇NoSuchElementException的解决及逐行打印方法

问题解决:NetBeans读取文本文件时NoSuchElementException异常

问题详情

在NetBeans中读取名为favouriteplace.txt的文本文件,期望按格式打印所有地点名称及对应评分,但运行代码时出现NoSuchElementException,仅成功打印第一条数据,其余内容无法迭代输出。

原代码

public class Praktikum11_4 {
    private Scanner input;
   
    public void membukaFile()
    {
        try {
            input = new Scanner(new File("favouriteplace.txt"));
        }   catch(FileNotFoundException e)
        {
            System.err.print("File yang anda cari" +
                    "Tidak ditemukkan");
            System.exit(1);
        }   catch(IllegalStateException e)
        {
            System.err.print("Error membaca File");
        }
        
    }
    
    public void membacaData()
    {
        try{
            while(input.hasNext())
            {   
                for (int i = 1 ; i <= 7 ; i++ )
                {
                    // Scan the line
                    String location = input.nextLine();
                    double rating = input.nextDouble();
                    System.out.printf(i+". " + "%s dengan rating %f\n", location, rating);
                }
            }
        }catch (NoSuchElementException e)
        {
            System.err.println("Element not found ERROR 101 ");
        }
    }
    
    public void menutupFile()
    {
        if (input != null)
        {
            input.close();
            System.out.print("File berhasil untuk ditutup");
        }
    }
    
    public static void main(String[] args)
    {
        
    }
}

当前输出

Five favourite place for UMN Student's
1. Bungkushin  dengan rating 4.300000
Element not found ERROR 101 
File berhasil untuk ditutup

输入文件内容

文件第一行是标题:Five favourite place for UMN Student's
后续每行按“地点名称+评分”交替排列,具体内容:

Bungkushin
4.3
Central Park
4.5
Trans Studio Bandung
4.2
Dufan
4.4
Taman Mini Indonesia Indah
4.1
Ragunan Zoo
4.0
Ancol Dreamland
4.6

期望输出

Five favourite place for UMN Student's
1. Bungkushin dengan rating 4.300000
2. Central Park dengan rating 4.500000
3. Trans Studio Bandung dengan rating 4.200000
4. Dufan dengan rating 4.400000
5. Taman Mini Indonesia Indah dengan rating 4.100000
6. Ragunan Zoo dengan rating 4.000000
7. Ancol Dreamland dengan rating 4.600000
File berhasil untuk ditutup

错误原因分析

  1. 核心逻辑未执行:原代码main方法为空,未调用membukaFile()、membacaData()、menutupFile()方法,导致读取流程未启动。
  2. 读取指针错位:input.nextDouble()读取评分后,指针停在数字末尾,不会自动跳过换行符。下一次input.nextLine()会读取空字符串,再调用nextDouble()时找不到有效元素,抛出异常。
  3. 循环逻辑错误:外层while嵌套内层硬编码的for循环,既会重复读取,也无法适配实际数据条数。
  4. 标题行未处理:直接读取地点数据,会把文件第一行标题当成第一个地点,导致后续读取全部错位。

修复后的代码

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Praktikum11_4 {
    private Scanner input;
   
    public void membukaFile() {
        try {
            input = new Scanner(new File("favouriteplace.txt"));
        } catch(FileNotFoundException e) {
            System.err.println("File yang Anda cari tidak ditemukan");
            System.exit(1);
        } catch(IllegalStateException e) {
            System.err.println("Error membaca file");
        }
    }
    
    public void membacaData() {
        try {
            // 先读取并打印标题行
            if (input.hasNextLine()) {
                System.out.println(input.nextLine());
            }
            
            int index = 1;
            // 循环读取每一组地点和评分
            while(input.hasNextLine()) {
                String location = input.nextLine();
                // 检查是否存在有效评分数据
                if (input.hasNextDouble()) {
                    double rating = input.nextDouble();
                    System.out.printf("%d. %s dengan rating %.1f\n", index++, location, rating);
                    // 跳过评分后的换行符,避免下一次读取空行
                    input.nextLine();
                } else {
                    break;
                }
            }
        } catch (NoSuchElementException e) {
            System.err.println("Element not found ERROR 101 ");
        }
    }
    
    public void menutupFile() {
        if (input != null) {
            input.close();
            System.out.println("File berhasil untuk ditutup");
        }
    }
    
    public static void main(String[] args) {
        Praktikum11_4 reader = new Praktikum11_4();
        reader.membukaFile();
        reader.membacaData();
        reader.menutupFile();
    }
}

修复说明

  1. 完善执行流程:在main方法中创建类实例,依次调用打开、读取、关闭文件的方法,确保完整执行读取流程。
  2. 处理标题行:先读取文件第一行标题并打印,再开始读取地点数据,避免错位。
  3. 修正读取逻辑:
    • 使用while(input.hasNextLine())动态循环,确保有数据时才读取。
    • 读取评分后调用input.nextLine()跳过换行符,解决指针错位问题。
    • 用递增的index替代硬编码循环次数,适配实际数据条数。
  4. 优化输出格式:使用%.1f控制评分小数位数,与期望输出一致。

内容的提问来源于stack exchange,提问作者Ryu Christian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:07:46