Forums Register Login

Using boolean to check if a number is binary or not

+Pie Number of slices to send: Send
Hi everyone I have recently started learning Java and this is my second post.I was trying to do some small programs and I found this small excercise on the web:

A binary number is written as combination of 1's and 0's.
Binary number 100 indicates 4.

Write a program which accepts a number and prints whether it is binary or not.

For Ex:

1) if user inputs 1040400
then it should print "Not Binary".

2) if user inputs 1000100
then it should print "Binary".




This is how my code looks like :




It is giving me the expected output but my question is if I can use a flag which can be set to 'FALSE' if the char array contains anything else than '0' or '1' instead of getting the count for numbers which are not '0' or '1'.

Please advice
+Pie Number of slices to send: Send
But the digits in a number do not determine whether a number is binary.
11000101 might be a binary number in 8 bits, which means 197 unsigned or -59 in two's complement, or even -69 in S&M. It also means 11million 1hundred and 1 in unsigned decimal.
Your tehnique will only find the characteristics of the String the number is written in. You can determine whether your String contains only the characters '0' and '1'; I would consider a loop a good way to do it, or a regular expression can find whether it matches. I would have used a while loop or a simple for loop; I don't think the for‑each loop is ideal.
+Pie Number of slices to send: Send
Yes, you can use a boolean as a flag in the loop; that will allow you to terminate the loop as son as you encounter something which isn't '0' or '1'.
+Pie Number of slices to send: Send
You can also use the % and / operators on the number itself without using a String.
1
+Pie Number of slices to send: Send
Victor Bogo, please note what it says on the contents page of this forum.

We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers.

It does not help the OP to work out his own answers if you simply provide a solution. I have pulled rank and deleted the post, though it is possible to retrieve it from archives later and restore it.
Sunglasses. AKA Coolness prosthetic. This tiny ad doesn't need shades:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2462 times.
Similar Threads
While loop
Array search code for hotel program
Need help with various methods
Not able to understand error
Ask user for 3 integers and find out if they make a triangle or not.
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 04:14:17.