In: Computer Science
Write a JAVA program that prompts the user to enter a character c that represents a binary digit (a bit!). (Recall that c can be only “0” or “1.”) Your program must use the character type for the input. If the user enters a character “x” that is not a bit, you must print out the following error message: “The character x is invalid: x is not a bit.” If the character c is a bit, your main program must print out its value in decimal. Example 1: If the user enters the character “0,” your program must print out the value 0. Example 2: If the user enters the character “1,” your program must print out the value 1. Example 3: If the user enters the character “B,” your program must print out the following error message: “The character B is invalid: B is not a bit.”
Code:
import java.util.Scanner;
//importing java scanner to take input from the user
public class Main {
public static void main(String[] args) {
Scanner scan = new
Scanner(System.in);
char n;
//taking input from the
user
System.out.print("Please
enter the Character: ");
//storing it in a
variable named "n"
n =
scan.next().charAt(0);
//checking whether the
input is 1 bit binary or not using if else condition
if(n=='0' ||
n=='1'){
//if the input is 1 bit binary number printing the number
System.out.println(n);
}
else{
//otherwise printing the error message
System.out.println("Character "+n+" is invalid: "+n+" is not a
bit");
}
}
}
Explanation:
The java code takes the character as input from the user
If the input is a 1 bit binary number i.e, "0" or "1" it will print the decimal value
Otherwise it will print he error message i.e
"The character is invalid: character not a Bit"
Screenshot of the Code:

Screenshot of the Output when the input is "1":

Screenshot of the Output when the input is "0":

Screenshot of the Output when the input is invalid character:
