Write a program that inputs a word representing a binary num

Write a program that inputs a word representing a binary number (0s and 1s). First, your program should verify that it is indeed a binary number, that is, the number only contains 0s and 1s. If that is not the case, your program should print a message that the number is not a valid binary number. Then, your program should count how many 1s are in that word and output the count.

Solution

import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException {
char c;
int count=0,len=0,i=0;
String str=\"\";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\"Enter the binary number :\");
str=br.readLine();
len=str.length();
while(i<len){
if(str.charAt(i)==\'1\' || str.charAt(i)==\'0\' ){
if(str.charAt(i)==\'1\')
count++;
}
else
break;
i++;
}

if(i==len){
System.out.print(\"\ \ The number contain \"+count+\" numbers of 1s\");
}
else
System.out.print(\"\ \ The number is not a valid binary number\");

}

}

Write a program that inputs a word representing a binary number (0s and 1s). First, your program should verify that it is indeed a binary number, that is, the n

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site