Question

How would I write code in Java, where the user inputs a binary number and the...

How would I write code in Java, where the user inputs a binary number and the system reads the input and outputs if there was an even or odd number of 1s typed. For example, if I typed 10101 it should output as odd. and if I typed 11011 it should output as even.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

BinaryEvenOddTest.java

import java.util.Scanner;


public class BinaryEvenOddTest {

   public static void main(String[] args) {
       Scanner console = new Scanner(System.in);
       System.out.println("Enter the binary number");
       int binary = console.nextInt();
       int countOnes = 0;
       while(binary > 0) {
           int r = binary % 10;
           if(r == 1) {
               countOnes++;
           }
           binary = binary/10;
       }
       if(countOnes % 2 == 0) {
           System.out.println("Number of 1's is Even");
       } else {
           System.out.println("Number of 1's is Odd");
       }
   }

}

Output:

Enter the binary number
10101
Number of 1's is Odd

Add a comment
Know the answer?
Add Answer to:
How would I write code in Java, where the user inputs a binary number and the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT