Last active
June 19, 2017 20:07
-
-
Save effective-light/5e211f87fff1f2f984ed0528388a4d8c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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