Converting binary to decimal using recursion
I made a method to convert from binary to decimal, but I also need to print an error message if the string I passed contains something other than 1's or 0's. I'm not sure where to implement that in my code...?
Code:
public int binToDec(String input){
int size = input.length();
if(size == 1){ return Integer.parseInt(input); }
else{
return binToDec(input.substring(1,size)) + Integer.parseInt(input.substring(0,1))*(int)Math.pow(2, size-1); }
}
Re: Converting binary to decimal using recursion
What happens currently when you pass the method a "bad" string?
-----
A question to think about is where the message printing will take place: in the method, or by the caller of the method.
Re: Converting binary to decimal using recursion
Well currently it will just return a wrong value. Although now that you mention it, I don't know why I didn't think of just prompting the user for a string, checking it, and then calling the method if it's okay. Ha ha, cause I'm currently just hard coding the string.
Re: Converting binary to decimal using recursion
Have you actually tested and verified that it returns the wrong value?
Testing the string and only calling the method for good strings is perfectly legitimate (how would you do the test?) But an alternative is to deal with what really happens when a bad string is passed.
Re: Converting binary to decimal using recursion
I think I got it. I wasn't taking into account that a bad string can include characters other than digits so I checked for that also and printed the message so it won't give me an error.