Quote (Wacko @ Jan 11 2015 02:33pm)
Code
public static int countUpper(String n){
assert n.isEmpty() == false;
int result;
if (n.length() == 0)
return 0;
result = Character.isUpperCase(n.charAt(0)) ? 1 : 0;
return countUpper(n.substring(1)) + result;
}
changed it up before you posted. Its mildly lazy i know, the professor was more concerned with the recursion than anything. He did say however error handling could be done using either assert or throwing an exception...so if in this instance assert is a bad choice i can always change it
And i guess im confused by what you mean about failing if the string is too small?
as for assert, it makes no sense to have it there. it's perfectly valid to have an empty string as input and return 0. in fact, it's necessary to have it there as your base case of the recursive method.
Quote
assert n.isEmpty() == false;
if (n.length() == 0)
you're asserting that it's not empty, but then immediately after you're checking if it's empty. that's a logical error.
as for parameter validation, it should be done using exceptions. eg if the user inputs null into your function, you're going to get a null pointer exception.
as for the substring:
From the link i posted:
Quote
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
from your code:
Quote
return countUpper(n.substring(1)) + result;
in your original code, this would fail if the length is 0. in your new code you fixed it by returning 0 before it gets here. i assume you found that by running it.