Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bufferedReader

 
gary davis
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
     
    Ernest Friedman-Hill
    author and iconoclast
    Marshal
    Pie
    Posts: 24211
    35
    Chrome Eclipse IDE Mac OS X
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic