Using BufferedReader to read input number from user


This example shows how to read input from console using the BufferedReader class. The BufferedReader has a neat method called readLine() that reads all the input characters into a string when the user hits the Enter button instead of reading byte by byte.
This example takes the input string and parses it into a variable of type Double and then prints out the square root of that number.
This is the code:


package com.javadb.examples;

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

/**
 *
 * @author www.javadb.com
 */

public class Main {

    public static void main(String[] args) {

        try {
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String input = reader.readLine();
            
            double number = Double.parseDouble(input);
            
            System.out.println("Square root of input number " + input + " is: " + Math.sqrt(number));
            
            //Not really necessary in this case but since we want to
            //write clean code...
            reader.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            System.out.println("Input by user was not a number.");
            e.printStackTrace();
        }
    }
}


So if we for example type in 12345, the output from the program looks like:


Square root of input number 12345 is: 111.1080555135405

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: