Home » Java Codes

Java File I/O – Using BufferedReader to read input number from user

13 February 2009 890 views One Comment

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

Tags: , , , , , , , , , , , , , ,

One Comment »

  • Marie said:

    thanksss.

Leave your response!

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>