5

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.

4 Answers 4

8

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 Strings.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for killing an ant with a sledgehammer. Which is really not fun for either the ant or the hammer.
2

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)

3 Comments

okay and how do you ask for two String inputs on the same line?
with Scanner you could use the scan.next() function but with bufferedreader? Thanks
Lines are distinguished based on "\n" which is enter.
2

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);

1 Comment

could you tell me how to ask for two String inputs on the same line? thanks
0

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);

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.