"If it were my assignment, I'd turn the string into an integer with Integer.parseInt() and then pick off the digits from right to left with the % and / operators until the residual value was 0. "
That would take care of any leading zero's or spaces in the string.
You can take the input number and % and / by 10 and then do whatever you want.
Joined: Oct 29, 2004
I must be missing something here.
This is my first programming class and the assignment is to develop a method to convert a binary value (11010011) to a decimal value (211).
I'm not sure what the best way to proceed is. I know the steps to do the conversion. I'm just not sure how to get JAVA to read one digit at a time.
Thanks again for your help.
Joined: Oct 12, 2004
This is what a number of us were trying to suggest to you with the code we posted above. You can think of String objects in Java as a sort of array: starting from the leftmost position, this is equivalent to the element at the first position in a Java array, with the index numbering starting from zero.
Thus in your string "1234567", character at index 0 is 1 character at index 1 is 2 character at index 2 is 3
... and so on up to the end of the string.
To find out the size of the String, and thus the size of the string "array", you can call the String.length() method on the String, to return an integer defining its length, i.e (number of characters in String) - 1, since numbering starts at index zero.
Thus to return the character at a particular index, you call the charAt() method on the string, thus myString.charAt(2), will return the char representation of the character at index 2, which in the case of the string "1234567" is the Unicode value corresponding to the character "3". So to go from right to left, you can use a for loop: for (int i = (myString.length()-1); i >= 0; i--) this tells the JVM: "initialise the int primitive i to the length of the string myString -1, i.e. the position of the rightmost character. Then, for as long as i is greater than or equal to zero, execute the expressions in the for loop, decrementing i by 1 after each pass through the loop". You can then read the characters one at a time from right to left on each pass through the for loop, convert them to integers using one of the methods described in the postings above, and use them to build up the value of your decimal total. OK?
Joined: Oct 29, 2004
You guys (and Gals) rock.
I think I understand what I need to do now. Thanks for all your help
I am working on a similar program in that I must read a number input by the user and give a count of the number of odd, even and zero digits. Will the tips given in this thread work for that? I have been trying it and can't get it to work. Any suggestions?