Accepting Input from the Keyboard - Java Language Basics

Java examples for Language Basics:Console

Introduction

Use java.io.BufferedReader and java.io.InputStreamReader classes to read keyboard entry and store it into local variables.

Demo Code

import java.io.*; 

public class Main { 
    public static void main(String[] args){ 
        BufferedReader readIn = new BufferedReader( new InputStreamReader(System.in)); 
        String numberAsString = ""; 
        long numberAsLong = 0; 

        boolean numberIsValid = false; 
        do { //from  w w  w  . j av  a2  s  .  c  o  m
            /* Ask the user for a number. */ 
            System.out.println("Please enter a number: "); 
            try { 
                numberAsString = readIn.readLine(); 
                System.out.println("You entered " + numberAsString); 
            } catch (IOException ex){ 
                System.out.println(ex); 
            } 

            /* Convert the number into binary form. */ 
            try { 
                numberAsLong = Long.parseLong(numberAsString); 
                numberIsValid = true; 
            } catch (NumberFormatException nfe) { 
                System.out.println ("Not a number!"); 
            } 
        } while (numberIsValid == false);   
    } 
}

Result


Related Tutorials