In the program below, the variable binary holds a four digit binary number saved into a String. Convert the number into decimal number, and output the decimal value into screen.
HINT: Use String method charAt() to check, whether the bits are ones or zeros!
import java.util.Random;
public class Test{
public static void output(String binary){
//////WRITE CODE IN HERE//////
}
public static void main(String[] args){
final Random r = new Random();
for (int i = 0; i %26lt; 4; i++){
String bin = "";
for (int j = 0; j %26lt; 4; j++){
bin += r.nextInt(2);
}
System.out.print("Binary string " + bin + " is in decimal: ");
output(bin);
}
}
}|||static double toDecimal (String s)
{
int l = s.length();
double result = 0;
for (int i = 0; i %26lt; l; i++)
{
result = result + s.charAt(i) * Math.pow(2, (s.length() - i - 1));
}
return result;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment