Results 1 to 5 of 5
- 10-13-2011, 10:52 PM #1
Member
- Join Date
- Jan 2011
- Posts
- 13
- Rep Power
- 0
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...?
Java 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); } }Last edited by _inase; 10-13-2011 at 11:30 PM.
- 10-14-2011, 12:59 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
- 10-14-2011, 01:15 AM #3
Member
- Join Date
- Jan 2011
- Posts
- 13
- Rep Power
- 0
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.
- 10-14-2011, 01:40 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
- 10-14-2011, 02:31 AM #5
Member
- Join Date
- Jan 2011
- Posts
- 13
- Rep Power
- 0
Similar Threads
-
anyone know's how to program a conversion of binary-decimal , decimal-binary
By irnie1994 in forum JCreatorReplies: 5Last Post: 08-25-2011, 07:32 PM -
Converting characters to decimal to binary
By Majeh in forum New To JavaReplies: 4Last Post: 02-04-2011, 11:06 PM -
Decimal to binary, octal to decimal
By matejm1994 in forum New To JavaReplies: 3Last Post: 12-26-2010, 09:59 AM -
Algorithm for converting binary/hex to decimal
By addictz04 in forum New To JavaReplies: 2Last Post: 11-29-2010, 06:49 PM -
converting decimal to binary value using recursion in java
By Anindo in forum New To JavaReplies: 3Last Post: 07-25-2009, 01:44 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks