Overclock.net banner

1 - 2 of 2 Posts

·
Registered
Joined
·
441 Posts
Discussion Starter · #1 ·
I am stuck on a small issue. I wrote a method for converting to decimal from binary, but I can't test to see if it works yet because I get an error when calling on the method and it is the only error. I identified the error as a comment in the code on line 12. Why is the method not working when I call it?

Here is the problem if that helps:


Code:

Code:
import java.util.Scanner;

public class BinaryConversion {

        public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                String str;

                System.out.println("Enter a binary number: ");
                str = input.nextLine();

                System.out.println("Conversion to decimal: " + binaryToDecimal(power)); // power cannot be resolved
        }

        public static int binaryToDecimal(String binaryString) {
                double power;

                power = 0;

                for(int i = 0; i < binaryString.length(); i++) {
                        if (binaryString.charAt(i) == '1') {
                                power = power + Math.pow(2, binaryString.length() - 1 - i); 
                        }
                }

                return (int)power;
        }

}
 

·
Registered
Joined
·
37 Posts
Quote:
Originally Posted by Heat Miser View Post

I am stuck on a small issue. I wrote a method for converting to decimal from binary, but I can't test to see if it works yet because I get an error when calling on the method and it is the only error. I identified the error as a comment in the code on line 12. Why is the method not working when I call it?
The problem is that the variable "power" does not exist in the main scope. It only exists in the function-scope.
The input from the console is stored in the "str" variable, so you need to pass that to the function.

Changing the line where the function is called to the following makes it work.

Code:

Code:
System.out.println("Conversion to decimal: " + binaryToDecimal(str));
 
1 - 2 of 2 Posts
Top