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

Java新手求助:使用BufferedReader读取字符输入时出现运行时错误

问题排查与解决方案

嘿,刚接触Java遇到这种输入问题太正常啦,我来帮你找出问题并修正~

你的代码出现运行时错误的核心原因

你用br.read()每次只读取单个字符,这里会碰到两个致命问题:

  1. 换行符被误读:当你输入第一个数字后按回车,这个回车(换行符\n)会被当成第二个字符读取,Character.getNumericValue()对换行符会返回-1,后续计算自然出错。
  2. 只能处理单数字:如果输入多位数(比如10),read()只会读取第一个字符1,剩下的0和换行符会被后续读取逻辑搞乱,完全不符合“两数相加”的需求。

另外你的代码最后一行System.out.println("\nSum o...")还没写完,这也是个小疏漏哦。

修正方案:用readLine()读取整行输入(推荐)

这种方式可以支持多位数输入,还能避开换行符的坑,是处理控制台输入更常用的方式:

package additio;
import java.io.*;
public class Additio {
    public static void main(String args[])throws Exception {
        BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
        System.out.println("Enter the first number:");
        // 读取第一行输入,转成整数
        int a = Integer.parseInt(br.readLine());
        
        System.out.println("Enter the second number:");
        // 读取第二行输入,转成整数
        int b = Integer.parseInt(br.readLine());
        
        int c = a + b;
        // 补全输出语句
        System.out.println("\nSum of the two numbers is: " + c);
    }
}

进阶优化:添加异常处理(让程序更健壮)

如果用户输入了非数字内容(比如字母),Integer.parseInt()会抛出NumberFormatException,可以加个try-catch块处理这种情况,避免程序直接崩溃:

package additio;
import java.io.*;
public class Additio {
    public static void main(String args[])throws Exception {
        BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
        
        try {
            System.out.println("Enter the first number:");
            int a = Integer.parseInt(br.readLine());
            
            System.out.println("Enter the second number:");
            int b = Integer.parseInt(br.readLine());
            
            int c = a + b;
            System.out.println("\nSum of the two numbers is: " + c);
        } catch (NumberFormatException ex) {
            System.out.println("哎呀,请输入有效的整数哦!");
        }
    }
}

如果你非要用字符读取(仅适合单数字场景)

如果只是想测试单数字相加的逻辑,需要手动跳过换行符:

char d=(char) br.read();
br.read(); // 跳过输入第一个数字后的换行符
char e=(char) br.read();

但这种方式实用性极低,不推荐用于实际的两数相加场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:56:32