【发布时间】:2021-12-31 17:10:12
【问题描述】:
我正在尝试制作一些分布式 Java RMI 程序,当我需要从用户那里获取输入时遇到了问题。在下面的代码sn-p中,输入1似乎很好,但是第一次输入2没有任何打印,当我再次输入2时,它就可以了。
这是怎么发生的?检查了BufferedReader.readLine() 函数文档,但没有发现任何与此相关的内容。这跟else if有关系吗?
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");
if (Integer.parseInt(lineOfText.readLine()) == 1) {
System.out.println("1 recieved");
} else if (Integer.parseInt(lineOfText.readLine()) == 2) {
System.out.println("2 recieved");
} else {
return;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
test t = new test();
}
}
输入1:
1 to create an auction, 2 to close an auction
1 //<- that's the input
1 recieved
输入2:
1 to create an auction, 2 to close an auction
2 //<- that's the input yet nothing happened
2 //<- input again
2 recieved
还尝试了一些在线编译器上的代码sn-p,结果和我的VSCode一样。这可能是一个简单的问题,但我不知道发生了什么;\
【问题讨论】:
-
if (readline == 1) { ... } else if (readline == 2) {...},问题是,您的第一个if语句正在停止从缓冲区读取输入,而2与1不匹配,因此它下降到else if哪个再次等待两者的输入。做一个 readline 然后检查结果。为简单起见,我还考虑使用Scanner -
是的,我找到了问题所在。之前使用
Scanner,但有点搞砸了,所以尝试了一些BufferedReader。
标签: java user-input bufferedreader readline