GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes bufferedReader Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "bufferedReader" Watch "bufferedReader" New topic
Author

bufferedReader

gary davis
Greenhorn

Joined: Nov 15, 2003
Posts: 7
I am new to Java programming and I would like to know how you can use bufferedReader to read an integer. The problem with the buffredReader it is returning the wrong number or just converting the number as a binary number.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in());
input = 0;
try
{
System.out.println("Enter an age");
input = input.read();
}
catch (IOException e)
{
if (input < 0)
System.out.println("Inut an Age: ");
else
System.out.println("An error has occured");
}
int correctAge = input;
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Gary,
Welcome to JavaRanch!
read() returns Unicode characters (essentially the same as ASCII here), not numbers. To read an integer from a BufferedReader, there are two steps:
  • First, read a line of input as a String;
  • Then, call a function to interpret the String as an integer.


  • This looks basically like this:

    Here "input" is a BufferedReader; you were using the same variable name to represent an int and a BufferedReader, which of course is not legal in Java -- a variable has to have a specific type.
    A few details: parseInt can throw NumberFormatException, so you should catch it; and whenever you construct a BufferedReader from System.in, you should pass 1 as the optional second argument, to turn off buffering, or you'll get some weird effects.
    One more thing: as this has nothing to do with networking, I'm moving it to the Java in General (Beginner) forum. Followups there, please.
    [ November 15, 2003: Message edited by: Ernest Friedman-Hill ]

    [Jess in Action][AskingGoodQuestions]
    Ernest Friedman-Hill
    author and iconoclast
    Marshal

    Joined: Jul 08, 2003
    Posts: 24187
        
      34

    In private email, Gary asks "Where would those lines of code go?" I'm answering here, so perhaps others might benefit.
    Rather than answer that, I'm going to show a fixed-up version of the code -- there are a number of other problems that need to be addressed.

    This version checks for negative numbers (your original seemed to assume negative input would throw an exception, which it wouldn't) and handles syntax errors in the input by catching NumberFormatException, thrown by parseInt(). Finally, it handles I/O errors by exiting the program -- the only sensible thing to do if there's an I/O error on stdin.
     
    GeeCON Prague 2014
     
    subject: bufferedReader