简体   繁体   中英

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.

my code for the 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:

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 . You already have the input in choose ; there is no need to call readLine every time you have a condition.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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