|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
