Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read integer

Status
Not open for further replies.

nirajj

Programmer
Mar 12, 2003
103
US
Hi all... This may sound novice but I am new to Java.. actually still learning.

I have the following lines of code to get an input
InputStreamReader reader = new InputStreamReader(System.in);
reader.read(charBuff);

However, I want to restrict the user input to only integer or float values. The user should not be able to input characters. Is it possible? If so, how to do it?

Thanks!
 
Probably the easiest way is to do :

float val = 0.0f;
try {
val = Float.parseFloat(charBuff);
} catch (NumberFormatException) {
// not a number - handle exception
}









--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Sounds to me, as if the input should be blocked between keyboard and screen ...
That's not possible, and therefore sedjs way is the way to go.
Print a useful message and repeat the action, if the user is thumb.

don't visit my homepage:
 
Thanks! I appreciate the inputs. :)
 
Hm, some other crazy idea. You could write a KeyListener. If the user presses a digit, print it. If he presses another button, make a warning sound. If he presses return, read the number.

But this would be far more complicated, and as you are a Java novice, this isn't the best way to do it. In most cases it's sufficent to try to convert the string, and to give an errormessage if there is an exception.
 
My 2cts. I would go for the GUI solution. Console applications that require user input are something from the "Dark Ages" of computing.
 
poster said:
I am new to Java.. actually still learning

Perhaps this is a learing excerise and the poster may not be ready for GUI's ?!

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I agree tom62 that GUI is the way to go. However, I want to follow the proper learning pattern and not skip any part. Yes sedj, it is part of my learning exercise.

I have actually moved on to GUI now. So far no major queries. But I am sure the Java gurus out here will be ready to help when I have some questions.

Thanks to everybody!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top