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

Java使用BufferedReader.readLine()首次输入2无响应问题排查

问题原因

你的代码问题核心是重复调用BufferedReader.readLine()方法,属于输入读取逻辑错误,和RMI框架、else if语法本身无关。
具体执行逻辑:

  • 程序运行后第一个if分支的lineOfText.readLine()会先读取用户第一次输入的内容
    • 若输入为1:判断为真,直接进入第一个分支打印输出,不会执行else if内的代码,逻辑符合预期
    • 若输入为2:第一次判断不成立,进入else if分支时会再次调用readLine()阻塞等待新的输入,所以第一次输入的2只会被用于第一个if的判断,需要第二次输入2才会被else if内的readLine()读取到,满足判断条件后打印输出。

修复方案

先一次性读取用户输入存储到变量中,再基于变量做分支判断即可:

import java.io.*;
public class test {

    private static BufferedReader lineOfText = new BufferedReader(new InputStreamReader(System.in));

    public test() throws NumberFormatException, IOException {
        System.out.println("1 to create an auction, 2 to close an auction");
        // 只调用一次readLine读取输入,存储到变量后再判断
        int userInput = Integer.parseInt(lineOfText.readLine());
        if (userInput == 1) {
            System.out.println("1 recieved");
        } else if (userInput == 2) {
            System.out.println("2 recieved");
        } else {
            return;
        }
    }
    public static void main(String[] args) throws NumberFormatException, IOException {
        test t = new test();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:24:02