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()读取到,满足判断条件后打印输出。
- 若输入为1:判断为真,直接进入第一个分支打印输出,不会执行
修复方案
先一次性读取用户输入存储到变量中,再基于变量做分支判断即可:
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
相关产品推荐
相关产品推荐

