简体   繁体   中英

Using BufferedReader to take input in java

I have been using the Scanner object to take in input until now and would like to learn how the BufferedReader works. I have tried it and it seems to be working only for Strings. can someone show me how to use it with ints and doubles?and how do you ask for two String inputs on the same line? Thanks.

Think of BufferedReader and Scanner as being at different levels of abstraction, rather than interchangeable parts that "do the same thing." I think this is the fundamental issue that you're hung up on.

BufferedReader is in some sense "simpler" than Scanner . BufferedReader just reads String s.

Scanner is much more robust than BufferedReader . It has APIs that make it easy for extracting objects of various types.

I could imagine Scanner being written using BufferedReader as an underlying building block. Whereas using Scanner to write BufferedReader would be like killing an ant with a sledgehammer.

Yes, bufferedreader will take only Strings. you need to convert them into int or double as required using Integer.parseInt(value) or Double.parseDouble(value)

BufferedReader basically takes a input stream as an argument.

You have to use in-built methods to parse string into ints and doubles .

Like :

BufferedReader br = new BufferedReader(new FileReader("input1.txt"))
String line = br.readLine();
//more logic here

 int number = Integer.parseInt(brstring);
 double number = Double.parseDouble(brstring);

This is how you can use it with String, int & double.

package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static  void main(String[] args)
        throws IOException
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        String name = bufferedReader.readLine();

        int number = Integer.parseInt(bufferedReader.readLine());                                              

        double d = Double.parseDouble(bufferedReader.readLine());

        System.out.println(name);

        System.out.println(number);

        System.out.println(d);

    }
}

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