I need to create a parseInt method from scratch and so far I'm getting it. The only part is I am having trouble figuring out how to find out if a int variable is overflowing or underflowing, and if it is then to throw an IllegalArgumentException in Java.
For better understanding this is my task:
Create static method parseInt(String) that converts a string into an int value, positive or negative. Method throws IllegalArgumentException when...
- A string contains non-digit characters other than '-' at (as the very first character of the sting).
- A string has only '-' and no digits.
- A string represents a number that is too large to be stored as integer and produces overflow
- A string represents a number that is too small to be stored as integer and produces underflow
Here is what I have so far
/**
* Convert a string into an integer value
* @param str The string to be converted
* @return answer
* @throws IllegalArgumentException if answer is underflowing or overflowing
*/
public static int parseInt(String str) throws IllegalArgumentException {
int answer = 0, factor = 1;
int i = 0;
for (i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
boolean isNegative = false;
if(str.charAt(0) == '-') {
isNegative = true;
}
if (answer > Integer.MAX_VALUE) throw new IllegalArgumentException();
if (answer < Integer.MIN_VALUE) throw new IllegalArgumentException();
if (isNegative) {
answer = -answer;
}
return answer;
}