In: Computer Science
Problem 4: Reading Binary You must write a program that will continuously prompt the user for a string representing a binary number. Then you should validate whether that string is valid binary number, and in case it is you must print the corresponding number in decimal base. Otherwise, you should state that the input string is not a valid binary number. Use the string “QUIT” to end the program. You should be aware that the input string may contain noise in the form of space characters. You must remove these characters from the string before testing whether it is a valid binary number. Your solution to this problem must contain three methods: • A method to remove the spaces. • A method to validate whether the string is a binary number • A method to convert the binary number string into an integer.
IN JAVA.
Code
import java.util.Scanner;
public class BinaryNumberCheck {
public static String removeSpaces(String input)
{
input = input.replaceAll(" ",
"");
return input;
}
public static boolean checkBinary(String input)
{
for(int i =
0;i
return false;
}
}
return true;
}
public static int binaryToInteger(String input)
{
int integer = 0;
for(int i = input.length()-1,
j=0;i>=0;i--,j++) {
int val =
input.charAt(i)=='1'?1:0;
integer +=
Math.pow(2, j) * val;
}
return integer;
}
public static void main(String args[]) {
boolean quit = false;
Scanner scan = new
Scanner(System.in);
while(!quit) {
System.out.println("Enter the binary number(QUIT to quit)");
String input =
scan.nextLine();
input =
removeSpaces(input);
if(checkBinary(input)) {
System.out.println("The Decimal is: " +
binaryToInteger(input));
quit = true;
}
}
}
}