C# Zero-One Multiple OverflowException using ULong - c#

I am trying to find the smallest zero-one number (a number that composes of only zeroes and ones i.e. 11001) that is a multiple of the number input through STDIN, but the program crashes when i input 99999, and this is one of the test cases that should work as the input value should range between 1 and 100000, the program crashes at
ulong.Parse(binary); in Getmultiple(ulong n).
What change should i make for it to work ?
class Program
{
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
ulong l;
ulong.TryParse(s, out l);
Console.WriteLine(Getmultiple(l));
}
}
private static ulong Getmultiple(ulong n)
{
for (ulong i = 1; ; i++)
{
String binary = Convert.ToString((long) i, 2);
ulong no = ulong.Parse(binary);
if (no % n == 0)
{
return no;
}
}
}
}
ERROR MESSAGE:
An unhandled exception of type 'System.OverflowException' occurred in
mscorlib.dll
Additional information: Value was either too large or too
small for a UInt64.

You're overflowing the unsigned long variable, meaning that there isn't a multiple of 99999 fitting your requirements that's also less than 2^64. If you refactor your code to use BigInteger instead of unsigned long, then you won't have the overflow problem. It might take some time for your algorithm to find the solution, though...
I'd also make this change, to sanity check your input:
BigInteger l;
if(BigInteger.TryParse(s, out l))
Console.WriteLine(Getmultiple(l));
else
Console.WriteLine("Not a valid integer");

looks like you are getting too large of a number for ulong no, you can use ulong.TryParse to avoid this.
private static ulong Getmultiple(ulong n)
{
for (ulong i = 1; ; i++)
{
String binary = Convert.ToString((long)i,2);
ulong no = 0;
if (ulong.TryParse(binary,out no))
{
if (no % n == 0)
{
return no;
}
}
else
{
return 0;
}
}
}
I chose to return 0 for an invalid result.

Using BigInteger works!! Some testcases that failed with ulong are now
working, thanks Esoteric Screen Name!
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
BigInteger l;
if (BigInteger.TryParse(s, out l))
Console.WriteLine(Getmultiple(l));
else
Console.WriteLine("Not a valid integer");
}
}
private static BigInteger Getmultiple(BigInteger n)
{
for (BigInteger i = 1; ; i++)
{
String binary = Convert.ToString((long) i, 2);
BigInteger no = BigInteger.Parse(binary);
if (no % n == 0)
{
return no;
}
}
}

Related

Nearest value from user input in an array C#

so in my application , I read some files into it and ask the user for a number , in these files there a lot of numbers and I am trying to find the nearest value when the number they enter is not in the file. So far I have as following
static int nearest(int close_num, int[] a)
{
foreach (int bob in a)
{
if ((close_num -= bob) <= 0)
return bob;
}
return -1;
}
Console.WriteLine("Enter a number to find out if is in the selected Net File: ");
int i3 = Convert.ToInt32(Console.ReadLine());
bool checker = false;
//Single nearest = 0;
//linear search#1
for (int i = 0; i < a.Length; i++)//looping through array
{
if(a[i] == i3)//checking to see the value is found in the array
{
Console.WriteLine("Value found and the position of it in the descending value of the selected Net File is: " + a[i]);
checker = true;
}
else
{
int found = nearest(i3,a);
Console.WriteLine("Cannot find this number in the Net File however here the closest number to that: " + found );
//Console.WriteLine("Cannot find this number in the Net File however here the closest number to that : " + nearest);
}
}
When a value that is in the file is entered the output is fine , but when it comes to the nearest value I cannot figure a way. I can't use this such as BinarySearchArray for this. a = the array whilst i3 is the value the user has entered. Would a binary search algorithm just be simpler for this?
Any help would be appreciated.
You need to make a pass over all the elements of the array, comparing each one in turn to find the smallest difference. At the same time, keep a note of the current nearest value.
There are many ways to do this; here's a fairly simple one:
static int nearest(int close_num, int[] a)
{
int result = -1;
long smallestDelta = long.MaxValue;
foreach (int bob in a)
{
long delta = (bob > close_num) ? (bob - close_num) : (close_num - bob);
if (delta < smallestDelta)
{
smallestDelta = delta;
result = bob;
}
}
return result;
}
Note that delta is calculated so that it is the absolute value of the difference.
Well, first we should define, what is nearest. Assuming that,
int nearest for given int number is the item of int[] a such that Math.Abs(nearest - number) is the smallest possible value
we can put it as
static int nearest(int number, int[] a)
{
long diff = -1;
int result = 0;
foreach (int item in a)
{
// actual = Math.Abs((long)item - number);
long actual = (long)item - number;
if (actual < 0)
actual = -actual;
// if item is the very first value or better than result
if (diff < 0 || actual < diff) {
result = item;
diff = actual;
}
}
return result;
}
The only tricky part is long for diff: it may appear that item - number exceeds int range (and will either have IntegerOverflow exceprion thrown or *invalid answer), e.g.
int[] a = new int[] {int.MaxValue, int.MaxValue - 1};
Console.Write(nearest(int.MinValue, a));
Note, that expected result is 2147483646, not 2147483647
what about LINQ ?
var nearestNumber = a.OrderBy(x => Math.Abs(x - i3)).First();
Just iterate through massive and find the minimal delta between close_num and array members
static int nearest(int close_num, int[] a)
{
// initialize as big number, 1000 just an example
int min_delta=1000;
int result=-1;
foreach (int bob in a)
{
if (Math.Abs(bob-close_num) <= min_delta)
{
min_delta = bob-close_num;
result = bob;
}
}
return result;
}

Pirate Game in Maths - Solve it with C#

I am trying to solve the following problem:
Some pirates have a chest full of treasure (gold coins)
It is late in the evening, so they decide to split it up in the morning
But, one of the pirates wakes up in the middle of the night concerned that
the other pirates will steal his share so he decides to go divide the
treasure himself.
He divides it into equal shares (one for each pirate). There is one
coin left over, which he throws overboard. He takes his share, puts the other shares back in the chest,
and returns to his cabin.
Another pirate wakes up and does the same thing. Yes, there is still
one extra coin. Yes, he throws that coin overboard.
... Each pirate does this once during the night (yes, there is an
extra coin and they throw it overboard each time) , and the next
morning they wake up and divide the treasure into equal shares. There
is one left over which they throw overboard. They each take their
share and live happily ever after.
Given the number of pirates, what is the smallest number of coins that
could have been in the treasure chest originally?
I tried the following, but any number greater than 8 brings it to its knees:
class Program
{
static long _input;
static long _timesDivided;
static string _output;
static void Main()
{
Console.WriteLine("Enter the number of Pirates: ");
var isValidInput = long.TryParse(Console.ReadLine(), out _input);
if (!isValidInput)
{
Console.WriteLine("Please enter a valid number");
Console.ReadKey();
return;
}
Console.WriteLine("Caculating minimum treasure...\r\n \r\n");
_timesDivided = _input + 1;
var answer = CalculateTreasure();
if (answer > 0)
_output = string.Format("The minimum treasure is {0}", answer);
else
_output = "There was an error, please try another number";
Console.WriteLine(_output);
Console.ReadKey();
}
private static long CalculateTreasure()
{
long result = 0;
try
{
while (true)
{
result++;
while (true)
{
if (result % _input == 1)
{
break;
}
else
{
result++;
}
}
long treasure = result;
for (long i = 0; i < _timesDivided; i++)
{
var remainder = treasure % _input;
if (remainder != 1)
{
break;
}
var share = (treasure - remainder) / _input;
if (i == (_timesDivided - 1))
{
treasure = (treasure - (share * _input));
if (treasure == 1)
return result;
}
else
{
treasure = (treasure - share) - 1;
}
}
}
}
catch (Exception ex)
{
//log exception here
return 0;
}
}
}
I am fairly certain that every number must be a prime number, so I have also attempted the above with that in mind. However, I have not been able to figure out an efficient formula for solving this. My maths is simply too weak
EDIT
Thanks to the video Fr3d mentioned, I now have this for my CalculateTreasure method:
private static long CalculateTreasure()
{
try
{
long result = (long)Math.Pow((double)_input, (double)_timesDivided);
while (true)
{
result--;
while (true)
{
if (result % _input == 1)
{
break;
}
else
{
result--;
}
}
long treasure = result;
for (long i = 0; i < _timesDivided; i++)
{
var remainder = treasure % _input;
if (remainder != 1)
{
break;
}
var share = (treasure - remainder) / _input;
if (i == (_timesDivided - 1))
{
treasure = (treasure - (share * _input));
if (treasure == 1)
return result;
}
else
{
treasure = (treasure - share) - 1;
}
}
}
}
catch (Exception ex)
{
//log exception here
return 0;
}
}
It is much improved, but still not 100% optimal
I think I found the correct formula:
using System;
using System.Numerics;
namespace PirateCoins
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Console.WriteLine(GetTreasure(n));
}
static BigInteger GetTreasure(int n)
{
BigInteger result = BigInteger.Pow(n, n + 1) - (n - 1);
return result;
}
}
}
This is based from a sequence which was given 2 -> 7, 3 -> 79, 4 -> 1021, 5 -> 15621 .

Pointers and fixed size buffers may only be used in an unsafe context

I have 2 functions within a class and getting error on the call for ParseBits() function i.e. "int num_elements = ParseBits(bits, buffer);" because of the "buffer" arguement I am passing "public int ParseBits(string bits, int* buffer)":
Function 1:
public float AssignFitness(string bits, int target_value)
{
//holds decimal values of gene sequence
int[] buffer = new int[(VM_Placement.AlgorithmParameters.chromo_length / VM_Placement.AlgorithmParameters.gene_length)];
int num_elements = ParseBits(bits, buffer);
// ok, we have a buffer filled with valid values of: operator - number - operator - number..
// now we calculate what this represents.
float result = 0.0f;
for (int i=0; i < num_elements-1; i+=2)
{
switch (buffer[i])
{
case 10:
result += buffer[i+1];
break;
case 11:
result -= buffer[i+1];
break;
case 12:
result *= buffer[i+1];
break;
case 13:
result /= buffer[i+1];
break;
}//end switch
}
// Now we calculate the fitness. First check to see if a solution has been found
// and assign an arbitarily high fitness score if this is so.
if (result == (float)target_value)
return 999.0f;
else
return 1/(float)fabs((double)(target_value - result));
// return result;
}
Function 2:
public int ParseBits(string bits, int* buffer)
{
//counter for buffer position
int cBuff = 0;
// step through bits a gene at a time until end and store decimal values
// of valid operators and numbers. Don't forget we are looking for operator -
// number - operator - number and so on... We ignore the unused genes 1111
// and 1110
//flag to determine if we are looking for an operator or a number
bool bOperator = true;
//storage for decimal value of currently tested gene
int this_gene = 0;
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i += VM_Placement.AlgorithmParameters.gene_length)
{
//convert the current gene to decimal
this_gene = BinToDec(bits.Substring(i, VM_Placement.AlgorithmParameters.gene_length));
//find a gene which represents an operator
if (bOperator)
{
if ((this_gene < 10) || (this_gene > 13))
continue;
else
{
bOperator = false;
buffer[cBuff++] = this_gene;
continue;
}
}
//find a gene which represents a number
else
{
if (this_gene > 9)
continue;
else
{
bOperator = true;
buffer[cBuff++] = this_gene;
continue;
}
}
}//next gene
// now we have to run through buffer to see if a possible divide by zero
// is included and delete it. (ie a '/' followed by a '0'). We take an easy
// way out here and just change the '/' to a '+'. This will not effect the
// evolution of the solution
for (int i = 0; i < cBuff; i++)
{
if ((buffer[i] == 13) && (buffer[i + 1] == 0))
buffer[i] = 10;
}
return cBuff;
}
I am getting 2 errors for this functions on the highlighted lines:
Error 1: The best overloaded method match for 'VM_Placement.Program.ParseBits(string, int*)' has some invalid arguments
Error 2: Pointers and fixed size buffers may only be used in an unsafe context
You need to enclose your function using raw pointers in an unsafe block.
unsafe
{
//your code
}
I had the same problem, but it wasn't solved by any of the other answers up here. I kept getting different errors.
Whatever functions use unsafe code simply need to be declared with the "unsafe" keyword.
For example:
static unsafe void myFunction(int* myInt, float* myFloat)
{
// Function definition
}
Personally, I was trying to do this when making a wrapper class.
For those interested, it ended up looking something like this:
using System.Runtime.InteropServices;
namespace myNamespace
{
public class myClass
{
[DllImport("myLib.so", EntryPoint = "myFunction")]
public static extern unsafe void myFunction(float* var1, float* var2);
}
}
Theres a lot of great information in the MSDN "Unsafe Code Tutorial":
https://msdn.microsoft.com/en-us/library/aa288474(v=vs.71).aspx
It's probably worth a read, I found it quite useful.
Perhaps I've missed it, but you don't appear to be doing anything that actually requires the use of a int*. Why not simply pass it an int array and change the ParseBits function signature to:
public int ParseBits(string bits, int[] buffer)
and remove the unsafe{ ... } blocks altogether.

inputs in methods at visual c# 2005

I am facing a problem in creating a console application in Visual Studio c# 2005
I created the following program in which a method (to sum 2 predefined values) is called in the program
here is the code of it
class program
{
static void Main()
{
program a;
a = new program();
Console.WriteLine(a.am1(1,2));
Console.ReadLine();
}
int sum;
public int am1(int num1, int num2)
{
sum = num1 + num2;
return sum;
}
}
Now here is the main problem I am facing, well in this program two integers (num1 and num2) are predefined, I wanted those 2 numbers to be taken from user, means user input the two numbers and then the same program goes on like above. How it should be done?
P.S remember everything should be done in methods
i hope i got your requirements ... if not, please elaborate!
public sealed class Program
{
private readonly int _number1;
private readonly int _number2;
public Program(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public int Sum()
{
return this._number1 + this._number2;
}
public static void Main(string[] args)
{
// this one here is really brutal, but you can adapt it
int number1 = int.Parse(args[0]);
int number2 = int.Parse(args[1]);
Program program = new Program(number1, number2);
int sum = program.Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
}
sry, this is not my main coding style ... pfuh ... really ugly!
edit:
don't give blind trust in int.Parse(). the params are coming from the user, you better double check them!
you better triple check them, as you are doing a sum ... thankfully c# compiles with unchecked - this code may fail with an OverflowException if compiled in vb - remember ranges of int
why do you want to do a simple addition in an extra class?
you should elaborate your style (regarding your comment): separate ui-code from business-layer code!
you do not need to create an instance variable for each task - you can do that with scope variables too...!
...
Use console application command line arguments. If it suites you. Below is an example from MSDN.
public class Functions
{
public static long Factorial(int n)
{
// Test for invalid input
if ((n < 0) || (n > 20))
{
return -1;
}
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Try to convert the input arguments to numbers. This will throw
// an exception if the argument is not a number.
// num = int.Parse(args[0]);
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Calculate factorial.
long result = Functions.Factorial(num);
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0 and <= 20.");
else
System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.

Best implementation for an isNumber(string) method

In my limited experience, I've been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea has always been the same, however, the implementation has been different. Some surround a parse attempt with try/catch
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
and others match with regex
public boolean isInteger(String str) {
return str.matches("^-?[0-9]+(\\.[0-9]+)?$");
}
Is one of these methods better than the other? I personally prefer using the regex approach, as it's concise, but will it perform on par if called while iterating over, say, a list of a several hundred thousand strings?
Note: As I'm kinda new to the site I don't fully understand this Community Wiki business, so if this belongs there let me know, and I'll gladly move it.
EDIT:
With all the TryParse suggestions I ported Asaph's benchmark code (thanks for a great post!) to C# and added a TryParse method. And as it seems, the TryParse wins hands down. However, the try catch approach took a crazy amount of time. To the point of me thinking I did something wrong! I also updated regex to handle negatives and decimal points.
Results for updated, C# benchmark code:
00:00:51.7390000 for isIntegerParseInt
00:00:03.9110000 for isIntegerRegex
00:00:00.3500000 for isIntegerTryParse
Using:
static bool isIntegerParseInt(string str) {
try {
int.Parse(str);
return true;
} catch (FormatException e){}
return false;
}
static bool isIntegerRegex(string str) {
return Regex.Match(str, "^-?[0-9]+(\\.[0-9]+)?$").Success;
}
static bool isIntegerTryParse(string str) {
int bob;
return Int32.TryParse(str, out bob);
}
I just ran some benchmarks on the performance of these 2 methods (On Macbook Pro OSX Leopard Java 6). ParseInt is faster. Here is the output:
This operation took 1562 ms.
This operation took 2251 ms.
And here is my benchmark code:
public class IsIntegerPerformanceTest {
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
public static void main(String[] args) {
long starttime, endtime;
int iterations = 1000000;
starttime = System.currentTimeMillis();
for (int i=0; i<iterations; i++) {
isIntegerParseInt("123");
isIntegerParseInt("not an int");
isIntegerParseInt("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i=0; i<iterations; i++) {
isIntegerRegex("123");
isIntegerRegex("not an int");
isIntegerRegex("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took " + (endtime - starttime) + " ms.");
}
}
Also, note that your regex will reject negative numbers and the parseInt method will accept them.
Here is our way of doing this:
public boolean isNumeric(String string) throws IllegalArgumentException
{
boolean isnumeric = false;
if (string != null && !string.equals(""))
{
isnumeric = true;
char chars[] = string.toCharArray();
for(int d = 0; d < chars.length; d++)
{
isnumeric &= Character.isDigit(chars[d]);
if(!isnumeric)
break;
}
}
return isnumeric;
}
If absolute performance is key, and if you are just checking for integers (not floating point numbers) I suspect that iterating over each character in the string, returning false if you encounter something not in the range 0-9, will be fastest.
RegEx is a more general-purpose solution so will probably not perform as fast for that special case. A solution that throws an exception will have some extra overhead in that case. TryParse will be slightly slower if you don't actually care about the value of the number, just whether or not it is a number, since the conversion to a number must also take place.
For anything but an inner loop that's called many times, the differences between all of these options should be insignificant.
I needed to refactor code like yours to get rid of NumberFormatException. The refactored Code:
public static Integer parseInteger(final String str) {
if (str == null || str.isEmpty()) {
return null;
}
final Scanner sc = new Scanner(str);
return Integer.valueOf(sc.nextInt());
}
As a Java 1.4 guy, I didn't know about java.util.Scanner. I found this interesting article:
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java
I personaly liked the solution with the scanner, very compact and still readable.
Some languages, like C#, have a TryParse (or equivalent) that works fairly well for something like this.
public boolean IsInteger(string value)
{
int i;
return Int32.TryParse(value, i);
}
Personally I would do this if you really want to simplify it.
public boolean isInteger(string myValue)
{
int myIntValue;
return int.TryParse(myValue, myIntValue)
}
You could create an extension method for a string, and make the whole process look cleaner...
public static bool IsInt(this string str)
{
int i;
return int.TryParse(str, out i);
}
You could then do the following in your actual code...
if(myString.IsInt())....
Using .NET, you could do something like:
private bool isNumber(string str)
{
return str.Any(c => !char.IsDigit(c));
}
public static boolean CheckString(String myString) {
char[] digits;
digits = myString.toCharArray();
for (char div : digits) {// for each element div of type char in the digits collection (digits is a collection containing div elements).
try {
Double.parseDouble(myString);
System.out.println("All are numbers");
return true;
} catch (NumberFormatException e) {
if (Character.isDigit(div)) {
System.out.println("Not all are chars");
return false;
}
}
}
System.out.println("All are chars");
return true;
}
That's my implementation to check whether a string is made of digits:
public static boolean isNumeric(String string)
{
if (string == null)
{
throw new NullPointerException("The string must not be null!");
}
final int len = string.length();
if (len == 0)
{
return false;
}
for (int i = 0; i < len; ++i)
{
if (!Character.isDigit(string.charAt(i)))
{
return false;
}
}
return true;
}
I like code:
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
But it will good more when create Pattern before use it:
public static Pattern patternInteger = Pattern.compile("^[0-9]+$");
public static boolean isIntegerRegex(String str) {
return patternInteger.matcher(str).matches();
}
Apply by test we have result:
This operation isIntegerParseInt took 1313 ms.
This operation isIntegerRegex took 1178 ms.
This operation isIntegerRegexNew took 304 ms.
With:
public class IsIntegerPerformanceTest {
private static Pattern pattern = Pattern.compile("^[0-9]+$");
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
}
return false;
}
public static boolean isIntegerRegexNew(String str) {
return pattern.matcher(str).matches();
}
public static boolean isIntegerRegex(String str) {
return str.matches("^[0-9]+$");
}
public static void main(String[] args) {
long starttime, endtime;
int iterations = 1000000;
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerParseInt("123");
isIntegerParseInt("not an int");
isIntegerParseInt("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation isIntegerParseInt took " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerRegex("123");
isIntegerRegex("not an int");
isIntegerRegex("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took isIntegerRegex " + (endtime - starttime) + " ms.");
starttime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
isIntegerRegexNew("123");
isIntegerRegexNew("not an int");
isIntegerRegexNew("-321");
}
endtime = System.currentTimeMillis();
System.out.println("This operation took isIntegerRegexNew " + (endtime - starttime) + " ms.");
}
}
I think It could be faster than previous solutions if you do the following (Java):
public final static boolean isInteger(String in)
{
char c;
int length = in.length();
boolean ret = length > 0;
int i = ret && in.charAt(0) == '-' ? 1 : 0;
for (; ret && i < length; i++)
{
c = in.charAt(i);
ret = (c >= '0' && c <= '9');
}
return ret;
}
I ran the same code that Asaph ran and the result was:
This operation took 28 ms.
A huge difference (against 1691 ms and 2049 ms -on my computer). Take in account that this method does not validate if the string is null, so you should do that previously (including the String trimming)
I think people here is missing a point. The use of the same pattern repeatedly has a very easy optimization. Just use a singleton of the pattern. Doing it, in all my tests the try-catch approach never have a better benchmark than the pattern approach. With a success test try-catch takes twice the time, with a fail test it's 6 times slower.
public static final Pattern INT_PATTERN= Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");
public static boolean isInt(String s){
return INT_PATTERN.matcher(s).matches();
}
I use this but I liked Asaph's rigor in his post.
public static bool IsNumeric(object expression)
{
if (expression == null)
return false;
double number;
return Double.TryParse(Convert.ToString(expression, CultureInfo.InvariantCulture), NumberStyles.Any,
NumberFormatInfo.InvariantInfo, out number);
}
For long numbers use this:
(JAVA)
public static boolean isNumber(String string) {
try {
Long.parseLong(string);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isNumber(String str){
return str.matches("[0-9]*\\.[0-9]+");
}
to check whether number (including float, integer) or not
A modified version of my previous answer:
public static boolean isInteger(String in)
{
if (in != null)
{
char c;
int i = 0;
int l = in.length();
if (l > 0 && in.charAt(0) == '-')
{
i = 1;
}
if (l > i)
{
for (; i < l; i++)
{
c = in.charAt(i);
if (c < '0' || c > '9')
return false;
}
return true;
}
}
return false;
}
I just added this class to my utils:
public class TryParseLong {
private boolean isParseable;
private long value;
public TryParseLong(String toParse) {
try {
value = Long.parseLong(toParse);
isParseable = true;
} catch (NumberFormatException e) {
// Exception set to null to indicate it is deliberately
// being ignored, since the compensating action
// of clearing the parsable flag is being taken.
e = null;
isParseable = false;
}
}
public boolean isParsable() {
return isParseable;
}
public long getLong() {
return value;
}
}
To use it:
TryParseLong valueAsLong = new TryParseLong(value);
if (valueAsLong.isParsable()) {
...
// Do something with valueAsLong.getLong();
} else {
...
}
This only parses the value once.
It still makes use of the exception and control flow by exceptions, but at least it encapsulates that kind of code in a utility class, and code that uses it can work in a more normal way.
The problem with Java versus C#, is that C# has out values and pass by reference, so it can effectively return 2 pieces of information; the flag to indicate that something is parsable or not, and the actual parsed value. When we reutrn >1 value in Java, we need to create an object to hold them, so I took that approach and put the flag and the parsed value in an object.
Escape analysis is likely to handle this efficiently, and create the value and flag on the stack, and never create this object on the heap, so I think doing this will have minimal impact on performance.
To my thinking this gives about the optimal compromise between keeping control-flow-by-exception out your code, good performance, and not parsing the integer more than once.
public static boolean CheckIfNumber(String number){
for(int i = 0; i < number.length(); i++){
try{
Double.parseDouble(number.substring(i));
}catch(NumberFormatException ex){
return false;
}
}
return true;
}
I had this problem before but when I had input a number and then a character, it would still return true, I think this is the better way to do it. Just check if every char is a number. A little longer but it takes care if you have the situation of a user inputting "1abc". For some reason, when I tried to try and catch without iterating, it still thought it was a number so..

Categories

Resources