• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using boolean to check if a number is binary or not  RSS feed

 
Greenhorn
Posts: 23
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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'.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use the % and / operators on the number itself without using a String.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!