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

如何通过BufferedReader接收字符并避免NumberFormatException

解决BufferedReader接收字符后出现NumberFormatException的问题

嘿,我来帮你搞定这个问题!你遇到的NumberFormatException其实是BufferedReader的输入处理逻辑导致的,我给你拆解清楚并提供几种靠谱的解决办法:

问题根源

BufferedReader.read()方法只会读取输入流里的单个字符,但当你输入字符(比如'A')后按下回车键,输入流里实际包含三个内容:目标字符、回车符(\r)、换行符(\n)。当read()取走目标字符后,剩下的\r\n还留在缓冲区里,接下来调用buf.readLine()时,它会直接读取到这个空的换行(readLine()会读取到换行符为止并自动丢弃换行符),相当于拿到了一个空字符串,这时候用Integer.parseInt()转换自然就抛出异常了。


方法一:读取字符后清空缓冲区剩余内容

在读取字符后,额外调用一次buf.readLine()来“吃掉”剩下的换行符,这样后续读取整数时就能拿到正确的输入:

System.out.println("Enter the type of pattern required"); 
char ch = (char) buf.read(); 
// 吃掉输入字符后残留的换行符
buf.readLine();
System.out.println("Enter the size"); 
int x = Integer.parseInt(buf.readLine()); 
switch(ch) { 
    case 'A': 
        // 你的业务逻辑
        break;
    // 其他case分支
}

方法二:用readLine()读取整行输入,再提取首字符

这种方法更稳妥,readLine()会一次性处理整行输入(包括换行符),我们只需要取输入字符串的第一个字符即可,还能兼容用户不小心输入多字符的情况:

System.out.println("Enter the type of pattern required"); 
// 读取整行并去掉前后空白(比如误输入的空格)
String input = buf.readLine().trim();
// 先校验输入是否为空,避免空指针异常
if (input.isEmpty()) {
    System.out.println("请输入有效的字符!");
    // 这里可以添加重新输入的逻辑
} else {
    char ch = input.charAt(0); 
    System.out.println("Enter the size"); 
    int x = Integer.parseInt(buf.readLine()); 
    switch(ch) { 
        case 'A': 
            // 你的业务逻辑
            break;
        // 其他case分支
    }
}

方法三:用Scanner类替代BufferedReader(更省心的方案)

如果不需要严格使用BufferedReader,Scanner类处理混合输入会更便捷,它会自动跳过空白字符(包括换行、空格):

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the type of pattern required"); 
// 读取一个以空白分隔的字符串,取第一个字符
char ch = scanner.next().charAt(0); 
System.out.println("Enter the size"); 
int x = scanner.nextInt(); 
switch(ch) { 
    case 'A': 
        // 你的业务逻辑
        break;
    // 其他case分支
}
scanner.close();

内容的提问来源于stack exchange,提问作者Kevin Andrew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:34:04