Skip to main content

If statement to not accept float numbers.

Please note these forums are being decommissioned and use the new and improved forums at
2 replies [Last post]
Joined: 2012-09-08

I'm new to the Java Programming world so I need help. I can't have much advanced help as being just a student 3 weeks into the course but I'm trying to be creative on my program but not sure how to get what I'm looking for.

Basically the user can input int values only and I want to make it where if they input a float like 5.5 that it tells them to only input whole numbers. How would I go about doing so?

I've tried...

if (A) = float))
System.out.println("Please Enter Whole Number Only! Thank You!");

but that's not going to work. So my question is how to get something like this to work?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2012-09-28

Try to perform Integer.parseInt(yourString) and if it throws a
NumberFormatException you'll know the string isn't a valid integer.

Joined: 2012-09-09

I assume that the input is being stored in a String variable. A quick way to differentiate between a whole number and a number with a decimal point is to scan the string for the presence of a decimal point, like so:

String input = "10.6";
boolean isDecimal = false;
for (int i = 0; i < input.length(); i++)
   if (input.charAt(i) == '.')
      isDecimal = true;

if (isDecimal)
   System.out.println("decimal point seen");

Of course, if your string can also accommodate an exponent, you would also have to check for the presence of letter e or E.

I hope this helps.