Using BufferedReader to read input number from user

package com.javadb.examples;

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


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

0 comments:

                                                                

Site Meter