Can someone explain how I would be able to go about adding string values to convert from base 10 to base 2?
I need to make a program that does the following:
• Ask the user for a number in the decimal (base 10) number system.
• Store this number into a variable with a suitable type and name
• Take this number and convert it into binary (base 2) using the algorithm learned in the previous unit. – take the number, divide it by two, keep track of the remainder, continue until you reach a quotient of 0.
• To find the remainder, you need to use the ‘mod’ function - %. 5%2=1 (5 divided by 2 is 2 remainder 1)
• It is possible to add to a variable of type String. (E.g. name = “C.I.”; name = “Lam” + name; c.print (name); - the output will be “LamC.I.”) – this is needed to keep track of your binary converted number
I have a bit of an understanding for the first few parts, it's only the string adding that is confusing me. My teacher said that 0 and 1 (the remainders of the mod to get to binary) should be treated as string values, and than get added together which kind of confuses me. I have, however managed to put together a program that gets the remainders, but the result comes out in the reversed order (for binary). Instead of 1011, I end up with 1101.
Any help would be much appreciated.
Adding strings to another creates a new string where all strings are appended in sequence. For example "B" + "A" + "C" = "BAC". You can use that in the example by creating an empty string and appending the remainders one by one. (Note: old string = old string + remainder, not vice versa or you'll get the wrong sequence) Do you know how to get a String value from an Integer? If not look up the class Integer in the javadoc.