문제

So my teacher is having us work with for loops and one of our assignments is to make a for loop that will change any base 2 number to base 10. I'll post what I have done so far. I'm only in AP Computer Science to the code will look amateurish.

    public long getBaseTen( )
{
    long ten=0;
    for (int i = 0; i < binary.length()-1; i++)
    {
        if (binary.charAt(binary.length()-i-1) == '0');
            ten += 0;
        if (binary.charAt(binary.length()-i-1) == '1');
            ten += Math.pow(2, i);
    }
    return ten;
}

binary is a string variable that contains the base 2 number earlier specified by the user. I need to convert this base 2 string into base 10 and store that number into long ten. Right now whenever I call this method, I always get the same number depending on the length of the string. If the string is 2 letters long, it will always return a 1, if it's 3 letters long, it will always return a 3, if it's 4 letters long, it will always return a 7 and so on. Help would be very much appreciated.

도움이 되었습니까?

해결책

The problem in your code is that your if-statements closes to early:

if (binary.charAt(binary.length()-i-1) == '0');
           ten += 0;

should be

if (binary.charAt(binary.length()-i-1) == '0'){
           ten += 0;
}

There are, of course, some other things that could be done differently, but you'll figure that out along the way.

다른 팁

Remove the semicolons at the end of the "if" lines. They shouldn't be there; they're being interpreted as

 if(whatever)
     ; // null statement -- do nothing

(You could also add braces around the block of code controlled by the if, but that's optional when you're just trying to control a single statement. Some folks always use the braces, but that decision is very much a matter of coding style.)

A string of 0's and 1's follows a power of two rule. The right most value is 2^0 then 2^1 2^2 and so on the exponent doubling each time. Knowing this you can make an easy for loop to do the conversion.

For example:

 int tens;
 for(int i=1;i<binary.length()-1; i++){
    tens += Math.pow(2,binary.length-i);
 }

For example if the binary number is 0101 we know this to be 5. We will start at binary.length()-1 which would be 3, perfect since the right most value 0 is represented by 2^3. The second number 1 is represented by 2^2 which if you notice binary.length()-i at this point is 2.

If you follow the logic this should work, may need a small syntax fix.

You are not need use one if statement, you can use this

public long getBaseTen()
{
    long ten=0;
    for (int i = 0; i < binary.length(); i++)
    {
        if (binary.charAt(i) == '1')
            ten += Math.pow(2,  binary.length()-i-1);
    }
    return ten;
}

Notice, i < binary.length()-1 it's wrong too.

You can see how it works here http://ideone.com/swzitQ

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top