How to Convert Binary to Decimal?

2019-06-10 00:24发布

问题:

I have almost completed this code, but it has told me that There is an illegal modifier in the public static int power; line. Can you guys please help?

public static int binToDec(int i)
{
    int[] numbers;//initialize variable
    int f = 4;
    String iString = "" + i;
    int result = 0;
    int length = iString.length();
    public static int power;
    for(power = iString.length(); power>=0;power--)
    {
    while(f == length && f >= 0)
    {

        numbers[power] = iString.charAt(power)^power;
    }

    length--;
    f--;
    }
    for(int g = 0; g <= numbers.length; g++)//double check constraints
    {
        result = numbers[g] = numbers[power];
    }

        return result;
}

回答1:

The modifiers public and static have no meaning for a local variable inside a method and are not valid there. The compiler error is suggesting that you remove them.



回答2:

Remove the "public static" in:

public static int power;


回答3:

In Java, static means that it's a variable or method within a class. In other words if you use static it has to belong to the scope of the whole class. If you move that line of code outside of your method it should fix your problem.



回答4:

You can do this.

int power = Istring.length(); And remove the initialization from for loop.



回答5:

Declaring and defining a variable inside a method will limit its scope to the method only. public is a keyword that is used to make it visible to every class out there and static makes the variable shared for whole class.

Therefore, public and static are not allowed for the method variables. Hence, only final keyword is permitted for such variables

Check this out for more on scope, default values and lifetime of method, instance and class variables