Currently I have an Atoi function in Java which returns an int value on passing a string input. The initial return value is set to 0. However, the value returned will be 0 if invalid characters or all characters are passed in input string and if the actual string passed is just “0”. How can I use return values for these two cases? Or is this okay and I should leave it upto the client to handle this ?
Share
You almost certainly shouldn’t use a return value in that situation – you should probably use an exception.
At that point though, I’m not sure why you’re writing your own method in the first place – use
Integer.parseIntinstead.If you need to be able to convey the notion of invalid input without an exception, you could potentially write a method which returns
Integerinstead ofint, and returnsnullif there’s invalid input, and an appropriateIntegerreference otherwise.(I’d also point out that Java tends to favour meaningful names, rather than somewhat arbitrary collections of letters such as
atoi.)