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

如何在非main方法中编写读写函数并修复Java未处理异常?

Java注册文本界面应用的未处理异常问题

我希望编写一个不在main方法中的写入函数,同时实现一个注册文本界面应用。以下是我的Java代码:

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class Tutorial6 {
    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       int choose;
       System.out.println("Enter your choice: ");
       choose = scanner.nextInt();
       if(choose == '1'){
          write();
}
       else{
          read();
}
    }

    public static void write() throws IOException, ClassNotFoundException{
       PrintWriter output = new PrintWriter(new FileWriter("users.txt", true));
       Scanner scanner = new Scanner(System.in);
       String name, address, ages;
       System.out.println("Enter your name: ");
       name = scanner.nextLine();
       System.out.println("Enter your address: ");
       address = scanner.nextLine();
       System.out.println("Enter your ages: ");
       ages = scanner.nextLine();

       output.println(name + " " + address + " " + ages + "\n");

       output.flush();
       output.close();

    }
    
        public static void read(){
       Scanner input = new Scanner (new File("users.txt"));
       while (input.hasNext())  {
           System.out.println(input.nextLine());
       }
       input.close();
    }
}

运行时出现“Unhandled exception type”错误,我曾尝试将读写函数放在不同类中可正常运行,但希望保持当前结构并解决该异常问题。


问题分析与修复方案

1. 未处理检查型异常

Java中IOException、FileNotFoundException属于检查型异常,必须显式处理:

  • write()方法抛出了IOException和多余的ClassNotFoundException(代码中未用到反序列化操作,可移除该异常声明)
  • read()方法创建Scanner(new File("users.txt"))时会抛出FileNotFoundException,但方法未声明或处理该异常
  • main方法调用write()时,未处理其抛出的异常

2. 输入逻辑错误

  • choose == '1'判断错误:choose是int类型,'1'是字符常量,两者值不匹配,应改为choose == 1
  • scanner.nextInt()读取整数后,输入缓冲区会残留换行符,导致后续scanner.nextLine()直接读取空字符串,需添加scanner.nextLine()清空换行

修复后的完整代码

import java.io.*;
import java.util.Scanner;

public class Tutorial6 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choose;
        System.out.println("Enter your choice (1: Register, other: View users): ");
        choose = scanner.nextInt();
        // 清空nextInt()残留的换行符
        scanner.nextLine();

        if (choose == 1) {
            try {
                write();
            } catch (IOException e) {
                System.err.println("写入失败: " + e.getMessage());
            }
        } else {
            try {
                read();
            } catch (FileNotFoundException e) {
                System.err.println("用户文件不存在: " + e.getMessage());
            }
        }
        scanner.close();
    }

    // 移除多余的ClassNotFoundException声明
    public static void write() throws IOException {
        // 使用try-with-resources自动管理流资源
        try (PrintWriter output = new PrintWriter(new FileWriter("users.txt", true))) {
            Scanner scanner = new Scanner(System.in);
            String name, address, age;

            System.out.println("Enter your name: ");
            name = scanner.nextLine();
            System.out.println("Enter your address: ");
            address = scanner.nextLine();
            System.out.println("Enter your age: ");
            age = scanner.nextLine();

            output.println(name + " " + address + " " + age);
        }
    }
    
    public static void read() throws FileNotFoundException {
        // 使用try-with-resources自动关闭Scanner
        try (Scanner input = new Scanner(new File("users.txt"))) {
            while (input.hasNext()) {
                System.out.println(input.nextLine());
            }
        }
    }
}

关键修改说明

  • 在main方法中用try-catch捕获读写方法抛出的异常,解决未处理异常报错
  • 移除write()方法中多余的ClassNotFoundException声明
  • 修正选择判断逻辑为choose == 1
  • 添加scanner.nextLine()处理整数输入后的换行符问题
  • 使用try-with-resources语法自动管理流资源,避免手动关闭流时的资源泄漏

内容的提问来源于stack exchange,提问作者thinh nguyen cong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:01:40