Overclock.net banner

Java - Converting to Decimal from Binary - Stuck on a Small Error

305 Views 1 Reply 2 Participants Last post by  QuietReading
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;
        }

}
See less See more
1 - 2 of 2 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));
  • Rep+
Reactions: 1
1 - 2 of 2 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top