Jump to content

Check for double:s

- - - - -

  • Please log in to reply
No replies to this topic

#1
Roman Y

Roman Y

    Programmer

  • Members
  • PipPipPipPip
  • 189 posts
Hi guys, this might be way to simple, this didn't actually hit me 'till recent. A while back I was writing a program that was taking a number of type double from the user for different purpuses... anyway since I didn't use Scanner I could go for .hasNextDouble() I had to check for myself if it was a valid input or not... The suggestions I've got was to check char for char if it was a digit, a coma, an "e", a + or - signes.... and it required a lot of writing and space... anyway I thought that it could've been done more simple using try-catch:

public class IfNumber 

{

	

	public static boolean doubleCheck(String numStr)

	{

		if(numStr.indexOf(".") >= 0) 	// Since dot is not a valid input from user 

			return false; 				// the method return false.

		

		numStr = numStr.replaceAll(",", "."); 	// Since "," is valid as input and at

		try										// the conversion at parse double the

		{										// machine needs to have a "." we replace

			double number = Double.parseDouble(numStr);	//"," with "."

			return true;

		}

		catch(NumberFormatException e)

		{

			return false;

		}

	}

		


}


same class could be used to create other static methods to check for integers, bytes, longs and other primitive number types.

hope I helped save people some time that I've could've save if I've come up with it a year earlier ^^

Edited by Roman Y, 07 August 2010 - 12:32 PM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users