Thursday, December 15, 2011

Binary to decimal java?

when compiling my program i get an error saying that they cannot find symbol for variable result here is the code


public static int toDecimal (String b)


{





int l = b.length();


int result = 0;


int num_1 = Integer.parseInt(b);








for (int i = 0; i %26lt; l; i++)


{


int power = 1;


for (int p = 1; p %26lt;= i; p++)


{


power = power * 2;





}


if (b.charAt(i) == '1')


{


result = result + power;





}


}


{return result;}


}


public static void main(String[] args) {











String b = "10";





System.out.println(" Decimal for " + b + " is " + result);


}


}


Any help would be much appreciated|||In your main() function, you are referencing variable "result". You did NOT declare it there. You declared that variable inside toDecimal() function.





First of all, make sure you understand what a scope is, and how it works with variables.





You can fix your problem by making result to be a static variable like this:





class test {


static int result;





public static int toDecimal (String b)


{





int l = b.length();


result = 0;


int num_1 = Integer.parseInt(b);








for (int i = 0; i %26lt; l; i++)


{


int power = 1;


for (int p = 1; p %26lt;= i; p++)


{


power = power * 2;





}


if (b.charAt(i) == '1')


{


result = result + power;





}


}


{return result;}


}


public static void main(String[] args) {











String b = "10";





System.out.println(" Decimal for " + b + " is " + result);


}


}








P.S. Your program does not convert the number correctly, but that's up to you to figure that out.|||There's a much easier way to covert that string to decimal.





public static int toDecimal(String b){


return parseInt(b, 2);


}

No comments:

Post a Comment