String to Long in Java

package Question1;

public class StringToLong {

public static void main(String[] args) {

StringToLong _StringToLong = new StringToLong();
_StringToLong.Test();
}

public void Test()
{
long i = 0;
String[] stringArray = {"123", "-123", "9223372036854775807", "-9223372036854775808", "a12" };

for (String obj : stringArray)
{
try
{
i = this.StringToLong(obj);

if (i == Long.parseLong(obj))
{
System.out.println(obj + ": ... success ...");
} else {
System.out.println(obj + ":... failure ...");
}

} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}

public long StringToLong(String str) throws NumberFormatException
{
long result = 0L, digit = 1L;

// Check Negative Number
boolean negativeNumber = false;

if(str.substring(0, 1).equals("-"))
{
negativeNumber = true;
str = str.substring(1);
}

// Check Number or not
if(!str.matches("^[0-9]+$"))
{
throw new NumberFormatException(str + " has Invalid Character");
}

for (int i = str.length() - 1; i >= 0; i--)
{
// number zero = ASCII code 48
result += ((long) str.charAt(i) - 48L) * digit;
digit *= 10;
}

// If Negative Number, go negative
if(negativeNumber)
{
result = -result;
}

return result;
}
}

Advertisements