I'm trying to write a program where I want the user to enter a positive whole numbers into the input box. I would also like to throw up a warning if they enter a decimal, letter, or negative number. I know how to do this with the negative condition, but I can't figure out how to do it for a decimal or letter. How do you tell java "if it isn't a whole number warn them? Please help I've been looking everywhere for this answer.

This is in a GUI, I take it? Do you want to validate as they type, or after they trigger a "submit" (via enter key or pushing a button or whatever)?

If it's the latter, just get the text as a String, see if it can be parsed as an int. If not, issue your warning. The Integer class will be able to tell you if this String can be parsed as an int - take a look at the methods of that class. If it's not a legit int, issue a warning. Otherwise, check that it's positive - if not, again, issue a warning.

If you want to check as they type, set up a keyListener on the component they're entering into, and use a keyTyped event to fire the same logic I just described.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.