简体   繁体   English

BufferedReader readline

[英]BufferedReader readline

I'm trying to use the bufferedReader for just practice, so every time I press enter in the console, it gives me the right answer, but not after one enter hit, I press enter more than once in order to get the result. 我正在尝试使用bufferedReader进行练习,因此,每次我在控制台中按Enter键时,它都会为我提供正确的答案,但是按回车键一次后,我多次按Enter键才能获得结果。

my code for the BufferedReader: 我的BufferedReader代码:

InputStreamReader irs = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String choose = br.readLine();

my if statement for the BufferedReader: 我的BufferedReader的if语句:

if ((choose = br.readLine()).equals("1)) {
            System.out.println("You chose: " + option1);
        } else if ((choose = br.readLine()).equals("2")) {
            System.out.println("You chose: " + option2);
        } else if ((choose = br.readLine()).equals("3")) {
            System.out.println("You chose: " + option3);
        }

the result from the console: 控制台的结果:

your choice: 

1

1

You chose: Dog

I should enter the choice more than once in order to get the result. 为了得到结果,我应该多次输入选择。 Any suggestion on how to correct that? 关于如何更正的任何建议? Thanks! 谢谢!

You are reading another line of input each time you call readLine . 每次调用readLine时,您正在读取另一行输入。 You already have the input in choose ; 您已经可以choose输入; there is no need to call readLine every time you have a condition. 每次有条件时都不需要调用readLine

Just use 只需使用

if ((choose.equals("1")) {

and similarly for the other conditions. 其他条件也一样。

choose = br.readLine();
if(choose.equals("1"))
//....
else if(choose.equals("2"))
//....
//and so on

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM