Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a program that inputs a string that represents a binary number. the string

ID: 3776950 • Letter: W

Question

write a program that inputs a string that represents a binary number. the string can contain only 0s and 1s and no other characters, not even spaces. validate that the entered number meets these requirements. if it does not, display an error message. if it is a valid binary number, determine the number of 1s that it contains. if it has exactly two 1s, display "Accepted". otherwise, display "Rejected". all input and output should be from the console. examples of invalid binary numbers: abc 10102011 10101ff 0000 1111 (note: contains a space). examples of valid ,rejected binary numbers: 00000000 1111 01110000001 examples of valid, accepted binary numbers: 1000001 1100. the following 3 test runs illustrate the of the program's console input and output: enter a binary number > abc invalid number. enter a binary number > 01110000001 rejected enter a binary number > 1000001 accepted. notes; 1.use the scanner class nextline method to input the binary number as a string. 2. use the string charAt() method in a "for" loop that varies the index of the character being examined. if your loop control variable is "I", then you will use charAt(i) in the loop body to be able to examine the character at position "i". as the loop progresses, you are able to get each character one by one. the characters in a string are indexed from 0 to 1 less than the number of characters in the string. The number of characters in the string can be determined by using length() method. 3. suppose you named the input string sinput. then your "for" loop header would look like: for (int i = 0; i <= sinput.length() - 1; i++) 4. note that charAt() returns a character as type "char". for comparison, remember that character literals are enclosed in single quotation marks, like this: '1'. 4. when an invalid String is detected, display an error message, and thgen use a "return" statement to exit fromn the main method. ending the program.

Explanation / Answer

import java.lang.*;
import java.util.*;
import java.util.Scanner;
class datavalid
{
public static void main(String args[])
{
String data;
Scanner sc=new Scanner(System.in);
data=sc.nextLine();
int count=0;
int flag=0;
for(int i=0;i<data.length();i++)
{
if(data.charAt(i)=='0' || data.charAt(i)=='1')
{
}
else
   {
   System.out.println("Invalid String");
flag=1;
break;
   }
}
if(flag==0)
{
for(int i=0;i<data.length();i++)
{
if(data.charAt(i)=='1')
{
count++;
if(count>2)
{
   break;
}
}
else
{
}
}
}
if(count==2)
System.out.println("Accepted");
else
System.out.println("rejected");
}
}