Skip to content

Instantly share code, notes, and snippets.

@effective-light
Last active June 19, 2017 20:07
Show Gist options
  • Save effective-light/5e211f87fff1f2f984ed0528388a4d8c to your computer and use it in GitHub Desktop.
Save effective-light/5e211f87fff1f2f984ed0528388a4d8c to your computer and use it in GitHub Desktop.
public class ParseTest
{
public static void main(String[] args)
{
if ( args.length == 1 )
System.out.println( ParseTest.parseInt( args[0] ) );
else
System.out.println( "Please supply an argument!" );
}
public static int parseInt(String str)
{
int result = 0;
boolean isNegative = str.charAt( 0 ) == '-';
String parsedStr = isNegative ? str.substring( 1 ) : str;
int place = parsedStr.length() - 1;
for ( int i = 0; i < parsedStr.length(); i++ )
{
char currentChar = parsedStr.charAt( i );
if ( !Character.isDigit( currentChar ) )
throw new NumberFormatException("Not an integer.");
result += Character.getNumericValue( currentChar ) * Math.pow( 10, place );
place--;
}
if ( isNegative )
result = -result;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment