Hey guys, need some serious help. Im building a program that can convert a binary number to decimal. My first thought was, that I could create an array containing the values of 1 depending of its position and then have the number typed in a textbox by the user, stored in an array, and after that, multiply both arrays, and finally, adding all the values up, giving me the conversion.
What I need to know is...
How do I store the int value into an array? for example, if the user types 1101, be stored like this:
after that, I want to multiply that array with another array already declared as:
So I can have the answer of the conversion as = 13
Please help, any example code is highly appreciated, Im new to java.
That is a real interesting route to go about it. I think you should take a look at the API for the Integer class. At the very least it will show you a Method of converting the user input String or character into a number. But you may find another useful method In there as well.
One thing all programmers need to learn is to break down problems into their discrete parts. I would never approach a problem like this as one thing to to, but at several. For example:
generating the numbers in the series 1,2,4,8... in a way I can get as few or as many as I need.
break a string down into individual characters
iterate through an array, looking at each element
get the input from a user
print some output.
store a bunch of characters into individual array elements
now...this is not the correct order that these will be used, but these are some of the things I need to do. If I can do each of these things (and notice how each and every one is completely independent of anything else), I can write the entire program you need. So now, I focus on writing a method for each of these. Note that some of these may in themselves need to be broken down into several steps/methods as well. But now I have a much smaller problem to focus on each time, making my job easier.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Tavo Gtz wrote:mmm, good point. Im trying to convert only integer.
OK, so now the question is: Are you doing this as a mental exercise, or is this part of some much larger problem?
If the first, then you should follow Fred and Steve's advice; if the latter, have a look at Integer.valueOf(String, radix) (all "integer" classes have something similar).
Joined: Mar 29, 2013
Actually, its part of a much bigger problem. I previously thought of using some type of conversion as the one you mention like : "Integer.toBinaryString(Variable)" but that type of solution is something that I can not use right now. Its part of a school assignment where you have to convert numeric systems, just the way you do it on a piece of paper.